我正在尝试使用Java的受保护范围进行练习。
我在package1中有一个基类:
package package1;
public class Base {
protected String messageFromBase = "Hello World";
protected void display(){
System.out.println("Base Display");
}
}
我在同一包中有一个Neighbor类:
package package1;
public class Neighbour {
public static void main(String[] args) {
Base b = new Base();
b.display();
}
}
然后,我在另一个包中有一个子类,该子类继承自package1的Base:
package package2;
import package1.Base;
class Child extends Base {
public static void main(String[] args) {
Base base1 = new Base();
base1.display(); // invisible
System.out.println(" this is not getting printed" + base1.messageFromBase); // invisible
}
}
我的问题是该display()
方法没有从子实例中调用。此外,base1.messageFromBase
尽管它们被声明为受保护的,但仍不可访问。
请注意有关protected
访问的一些事项
-They are available in the package using object of class
-They are available outside the package only through inheritance
-You cannot create object of a class and call the `protected` method outside package on it
它们只能通过包外部的继承来调用。您不必创建基类的对象然后调用,您只需调用display()
class Child extends Base {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
Makoto专家在提供的答案中提供了官方记录的链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句