本文主要是介绍吃透Java基础一:Java访问权限修饰符,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
同类 | 同包 | 同包子类 | 不同包子类 | 不同包 | |
---|---|---|---|---|---|
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();报错}
}
这篇关于吃透Java基础一:Java访问权限修饰符的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!