I am trying an exercise with Java's protected scope.
I have a Base class in package1:
package package1;
public class Base {
protected String messageFromBase = "Hello World";
protected void display(){
System.out.println("Base Display");
}
}
and I have a Neighbour class in same package:
package package1;
public class Neighbour {
public static void main(String[] args) {
Base b = new Base();
b.display();
}
}
Then I have a child class in another package, which inherits from Base from package1:
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
}
}
My problem is that the display()
method is not getting called from the child instance. Also, base1.messageFromBase
is not accessible although they are declared as protected.
Note some things about protected
access
-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
they are only called through inheritance outside package. You do not have to create object of base class and then call, you can simply call display()
class Child extends Base {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
An expert Makoto has provided the link for official documention in the answer he has provided.