同类 | 同包 | 同包子类 | 不同包子类 | 不同包 | |
---|---|---|---|---|---|
public | √ | √ | √ | √ | √ |
protected | √ | √ | √ | √ | |
包访问权限 | √ | √ | √ | ||
private | √ |
下面看例子:
base包下定义Father类,四种权限定义方法
package base;
public class Father {
public void showPublic() {
}
protected void showProtected() {
}
void showFriendly() {
}
private void showPrivate() {
}
}
同包子类
package base;
public class Son extends Father {
public static void main(String[] args) {
Son son = new Son();
son.showPublic();
son.showProtected();
son.showFriendly();
// son.showPrivate();报错
}
}
同包其它类
package base;
public class Other {
public static void main(String[] args) {
Father father = new Father();
father.showPublic();
father.showProtected();
father.showFriendly();
// father.showPrivate();报错
}
}
不同包子类
package text;
import base.Father;
public class AnotherSon extends Father {
public static void main(String[] args) {
AnotherSon anotherSon = new AnotherSon();
anotherSon.showPublic();
anotherSon.showProtected();
// anotherSon.showFriendly();报错
// anotherSon.showPrivate();报错
}
}
不同包其它类
package text;
import base.Father;
public class Another {
public static void main(String[] args) {
Father father = new Father();
father.showPublic();
// father.showProtected();报错
// father.showFriendly();报错
// father.showPrivate();报错
}
}