public class Person {
//用private修饰的变量,在其它类中不能直接访问 private int age; void speak(){ System.out.println("I‘am a person, my age:"+age); } } class PersonTest{ public static void main(String[] args) { Person person=new Person();
//虽然负数也是int类型,但我们知道一个人的年龄不能是负数
//需要我们写一些语句去判断正负 person.setAge(-20); person.speak(); } }
private实现了对类的属性的封装,但是其它类不能直接访问private属性,即使在其它类里面创建了类的对象也不能。
如果在其它类中要访问是私有的属性,常见的作法是调用geter和setter方法。
如下:
public class Person { private int age; public int getAge() { return age; } public void setAge(int age) { if(age>0 && age<130) { this.age = age; }else{ System.out.println("Age is not right,please check your input."); } } void speak(){ System.out.println("I‘am a person, my age:"+age); } } class PersonTest{ public static void main(String[] args) { Person person=new Person(); person.setAge(20); person.speak(); } }
原文:https://www.cnblogs.com/majestyking/p/12382053.html