javainheritanceprotected

accessing a method through subclass of a class in which the method is protected


STRUCTURE

src

├── pkg
│   ├── subpkg1
│   │   └── restaurant.java
│   ├── subpkg2
│       ├── H.java
│       └── test2.java

file name= restaurant.java

package pkg.subpkg1;

public class restaurant {

    public String name = "Domino";

    protected void open() {
        System.out.println("The restaurant is open");
    }

}

file name= H.java

package pkg.subpkg2;

import pkg.subpkg1.restaurant;

public class H extends restaurant {

}

file name= test2.java

package pkg.subpkg2;

public class test2 {

    public static void main(String[] args) {
        H r1 = new H();

        r1.open(); 

        System.out.println(r1.name);
    }

}

Error:

open() has protected access in restaurant

I expected that I would be able to get the "open" method from the instance of H class.


Solution

  • The use of protected means the method can only be called by classes in the same package (pkg.subpkg1) or by subclasses of the class declaring the method. test2 is not in pkg.subpkg1 and it is also not a subclass of restaurant so it cannot access open().

    If you want to be able to call it from test2, then it must either be declared public, or you need to move test2 to pkg.subpkg1, or H needs to override the method open() to declare it as protected so it's available to the current package:

    package pkg.subpkg2;
    
    import pkg.subpkg1.restaurant;
    
    public class H extends restaurant {
    
        @Override
        protected void open() {
            super.open();
        }
    
    }
    

    This only works if you declare the variable (r1 in your code) as an H. This wouldn't work when you declare r1 as a restaurant.

    As an aside, please familiarize yourself with the Java naming conventions. Class names should use CamelCase (i.e. Restaurant and Test2, not restaurant and test2).