public private protected default
这几个限定访问控制符只是在编译阶段起作用,在运行阶段不起作用
private修饰符 , 本类可以访问
default修饰符 , 本类,本包可以访问 (这是默认的,即什么都不写)
protected修饰符 ,本类,本包,子类可以访问
public修饰符 , 都可以访问
关于protected修饰符
protected是用来让子类可以访问父类的方法和属性的
必须有子类,而与子类所在的位置没有关系
对象是子类类型,当有多个子类时,必须是在本子类当中
package com.moreas.concurrency; public class Person { private String name;
int age;
protected String color; public Person() {
} public Person(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
} public void say() {
System.out.println(this.name + " say: I am " + this.color + " Person");
}
}
package com.moreas.concurrency.c; import com.moreas.concurrency.Person; public class BlackPerson extends Person { public static void main(String[] args) { BlackPerson p1 = new BlackPerson();
System.out.println("color:" + p1.color);//protected Person p2 = new BlackPerson(); //对象不是子类类型
//String col = p2.color; //编译出错
} }
package com.moreas.concurrency.c; import com.moreas.concurrency.Person; public class Other extends Person { public static void main(String[] args) { BlackPerson p1 = new BlackPerson();
// System.out.println("color:" + p1.color);//protected //编译出错,不是在本子类当中
} }
下面是错误的理解,以为只要是在子类当中,就可以访问protected属性了