//Person.java public class Person{ String name; char sex; Birthday birth; double height; Person(String name,char sex,Birthday birth,double height){ this.name=name; this.sex-sex; this.birth=birth; this.height=height; 髻人民邮电出版社 OSTS TELECOM PRESS
//Person.java public class Person { String name; char sex; Birthday birth; double height; Person(String name, char sex, Birthday birth, double height) { this.name=name; this.sex=sex; this.birth=birth; this.height=height; }
void show System.out.println("姓名:"+name); System.out.println("性别:"+sex); birth.showO); System.out.println("性别:"+height); //Birthday.java public class Birthday{ 人民邮电出版社 POSTS TELECOM PRESS
void show() { System.out.println("姓 名:"+name); System.out.println("性 别:"+sex); birth.show(); System.out.println("性 别:"+height); } } //Birthday.java public class Birthday { … }
3。域的访问控制 ①类的内部: 类的域在类的里面都是可见的,类中的 所有方法都可以使用他们。 ②类的外部:访问权限修饰符 在类的外部,类中域的可见性由关键字 public、private、protected来控制。这些关键 字限定了该类的具体对象在类的外部对域的 访问权限。 爹人民邮电出版社 OSTS TELECOM PRESS
3.域的访问控制 类的内部: 类的域在类的里面都是可见的,类中的 所有方法都可以使用他们。 类的外部:访问权限修饰符 在类的外部,类中域的可见性由关键字 public、private、protected来控制。这些关键 字限定了该类的具体对象在类的外部对域的 访问权限
Java中类成员(域和方法)共有4种访问权限: ◇public:可以被任何类访问。 ◇private:只能被所属的类访问。 ◇protected:可以被所在的类、同一包 的其他类和不同包的子类访问; ◇缺省的:只能被同一包的类访问。 人民邮电出版社 POSTS TELECOM PRESS
Java中类成员(域和方法)共有4种访问权限: public:可以被任何类访问。 private:只能被所属的类访问。 protected:可以被所在的类、同一包 的其他类和不同包的子类访问; 缺省的:只能被同一包的类访问
例3.3在类的外部试图访问和修改该类的私 有域将出现编译错误。 //TestPerson.java public class TestPerson public static void main(String args[){ Person obj=new Person("张三",'男',new Birthday(I988,8,8),1.75); obj.showO; System.out.println(" 改变类中变量的取值 obj.name="王立"; obj.birth=new Birthday(1988,1,20); obj.birth.show0); obj.showO; 人民邮电出版社 OSTS TELECOM PRESS
例3.3 在类的外部试图访问和修改该类的私 有域将出现编译错误。 //TestPerson.java public class TestPerson { public static void main(String args[]) { Person obj=new Person("张三", '男', new Birthday(1988,8,8), 1.75); obj.show(); System.out.println("========改变类中变量的取值=========="); obj.name="王立"; obj.birth=new Birthday(1988,1,20); obj.birth.show(); obj.show(); } }