简体   繁体   中英

Why protected scope is not working?

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.

You're using the parent class, not the child class, when you're attempting to call the protected method and access the protected field. Since you're inside of main , not using an instance of Child , and not in the same package as Base , you won't have access to the field or method through the parent alone.

You should create a new instance of Child can invoke the methods you want instead.

 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);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM