Why is the protected area not working?

I am trying to do an exercise with Java protected area.

I have a base class in package 1:

package package1;

 public class Base {

     protected String messageFromBase = "Hello World";

    protected void display(){
        System.out.println("Base Display");
    }

}

      

and I have a Neighbor class in the 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 that 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 method is display()

not getting called from the child instance. It is also base1.messageFromBase

not available, although they are advertised as protected.

+3


source to share


2 answers


Please note some of the protected

access details

-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 called only through inheritance outside of the package. You don't need to create an object of the base class and then call, you can just calldisplay()



class Child extends Base {
 public static void main(String[] args) {
    Child child = new Child();
    child.display(); 
  }
}

      

Expert Makoto provided a link to the official documentation in the answer he provided.

+7


source


You are using the parent class, not the child class, when you try to call a protected method and access the protected field. Since you are inside main

, not using an instance Child

, and not in the same package asBase

, you will not have access to a field or method only through the parent.

You must create a new instance Child

that can call the methods you want.



 class Child extends Base {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
        System.out.println(" this will get printed" + child.messageFromBase);

    }
}

      

+1


source







All Articles