私有(private
)访问修饰符只能在类中访问,四种访问修饰符,在本类中都可以访问,这边就不作代码验证了。
定义一个Person类:
package com.heima.jedis;
public class Person {
//默认的方法 default
void defaultMethod(){
}
//受保护的方法 protected
protected void protectedMethod(){
}
//公用方法 public
public void publicMethod(){
}
}
验证同包下的访问情况,创建C类,与Person同包:
结论:类 C 和 Person 同包,Person下的 public protected default 方法都可以访问
package com.heima.jedis;
public class C {
public void run(){
Person person = new Person();
//类 C 和 Person 同包 public protected default 都可以访问
person.publicMethod();
person.protectedMethod();
person.defaultMethod();
}
}
验证不同包下,继承关系下,子类访问父类方法的情况:
结论:不同包下的子类,通过创建父类来访问,也只能访问父类的public方法,
不同包下的子类,在子类中通过创建子类来访问父类的方法,可以访问 public 和 protected,但是无法访问default方法。(注意:这边说的在子类中创建子类,而不是在别的不相关的类中创建子类来访问,这样是访问不到的)
package com.heima.other;
import com.heima.jedis.Person;
public class Student extends Person {
public void run(){
//通过Person来访问
//类 C 和 Person 不同包,存在继承关系,通过Person 只能访问 public 方法
Person person = new Person();
person.publicMethod();
//报错:The method protectedMethod() from the type Person is not visible
//person.protectedMethod();
//报错:The method defaultMethod() from the type Person is not visible
//person.defaultMethod();
//通过继承关系 Student来访问,可以访问 public 和 protected 方法
Student student = new Student();
student.publicMethod();
student.protectedMethod();
//报错:The method defaultMethod() from the type Person is not visible
//student.defaultMethod();
}
}
验证不同包下,不存在继承关系的类访问Person类的情况
结论:不同包下的无关类,只能访问到Person的public方法。
package com.heima.other;
import com.heima.jedis.Person;
public class A {
public void run() {
Person person = new Person();
// 类 C 和 Person 不同包,且不存在继承关系,只能访问 public 方法
person.publicMethod();
//报错:The method protectedMethod() from the type Person is not visible
//person.protectedMethod();
//报错:The method defaultMethod() from the type Person is not visible
//person.defaultMethod();
}
}