Why subclass in another package cannot access a protected method?

how to access protected method from different package in java
protected method java
java access modifiers table
different package subclass example
access modifiers and access specifiers in java
which access specifier represents package level accessibility
default access specifier in java
private methods of superclass is not inherited by the subclass

I have two classes in two different packages:

package package1;

public class Class1 {
    public void tryMePublic() {
    }

    protected void tryMeProtected() {
    }
}


package package2;

import package1.Class1;

public class Class2 extends Class1 {
    doNow() {
        Class1 c = new Class1();
        c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
        tryMeProtected();  // No error
    }    
}

I can understand why there is no error in calling tryMeProtected() since Class2 sees this method as it inherits from Class1.

But why isn't it possible for an object of Class2 to access this method on an object of Class1 using c.tryMeProtected(); ?

Protected methods can only be accessible through inheritance in subclasses outside the package. And hence the second approach tryMeProtected(); works.

The code below wont compile because we are not calling the inherited version of protected method.

 Class1 c = new Class1();
 c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1

Follow this stackoverflow link for more explaination.

Protected member access from different packages in java, Protected methods can only be accessible through inheritance in subclasses outside the package. And hence the second approach tryMeProtected(); works. Call protected method from a subclass of another instance of different packages. I want to invoke a protected method of another instance from within a subclass of the class providing this protected method.

Can we access protected methods in different packages?, Its very simple to access protected methods from another packages protected Many people believe that they can't do anything to protect their privacy online,  Reading the tutorial even several times doesn't give a clue, why you cannot access protected member of an object of class Alpha from another object of another package, whose class AlphaSub is a subclass of Alpha. Actually, Java Language Specification explains this, e.g. in JLS 8: 6.6.2 Details on protected Access

You use two different packages and you don't access your parent attributes by direct inheritance, but by an intermediate parent instance declared in the child class (similar to composition). => that's the not the way protected works.

Only direct inheritance allows protected parent's attributes to be reach.

Thus, you can do this:

public class Class2 extends Class1 {
    doNow() {
        tryMeProtected();  // No error since direct inheritance 
    }    
}

but never this:

public class Class2 extends Class1 {
    doNow() {
        Class1 c = new Class1();
        c.tryMeProtected(); // this is not a direct inheritance! since `c`, although a parent one is an intermediate instance created in the child instance. => bad
    }    
}

Indeed, this is a particularity of protectedkeyword often misunderstood.

Java Access Modifiers, Visible to the package and all subclasses (protected). A variable or method declared without any access control modifier is available to any other class in Class and interfaces cannot be private. However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Ungulate.Eat legally from Giraffe, but we can't call the protected method Zebra.Eat from anything except Zebra or a subclass of Zebra. Since the compiler cannot determine from the static analysis that we are not in this illegal situation, it must flag it as being illegal. Incidentally, C++ has the same rule.

As per Java Protected Access modifier definition methods which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

you can't access protected method by creating object of class. So for accessing Protected method you have to extend the superclass.(this explains your 2nd call is correct)

What if my nested class extends another class from another package , default (package) Access Modifier; protected Access Modifier; public Classes, fields, constructors and methods can have one of four different Java access Code inside subclasses cannot access the variable or method, nor  A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object. It means that subclass from other package cannot access protected members of arbitrary instances of their superclasses,

It can be acheived by two ways

1. Either by making an object of Child class and then accessing the protected method of Parent class.

PACKAGE 1

public class Class1 {
    protected void m1() {
        System.out.println("m1 called");
    }
}

PACKAGE2

public class Class2 extends Class1 {

    public static void main(String[] args) {
        Class2 class2 = new Class2();
        class2.m1();
    }
}

2. Or by directly calling the method from the Child class

eg tryMeProtected();

Why subclass in another package cannot access a protected method?, You'd like to be able to protect these personal variables and methods at the language level and disallow access by objects of another type. The private protected access level is not supported in versions of Java higher than 1.0; you should no longer be using it in your Java Specifier, class, subclass, package, world. protected allows access from subclasses and from other classes in the same package. That's why any Derived class instance can access the protected method in Base. The other line creates a Base instance (not a Derived instance!!). And access to protected methods of that instance is only allowed from objects of the same package.

Java - Access Modifiers, Definitions: A class that is derived from another class is called a subclass (also a The Object class, defined in the java.lang package, defines and implements However, if the superclass has public or protected methods for accessing its  "The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package." This means the protected member must be accessed directly through either the class it is defined in or a subclass of said class while also being within the

Java Access Modifiers, The protected modifier allows special access permissions for subclasses. visible to subclasses of the class, even if they are defined in a different package. public method in a subclass, the reverse is not possible; you can't override a public  The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package. The following table shows the access to members permitted by each modifier.

Controlling Access to Members of a Class, A package groups related classes and interfaces and provides access { //​package access System.out.println("iampackage Method"); } protected void DeltaOne cannot refer to the iamprivate variable or invoke privateMethod but can access The next class, AlphaTwo , is a subclass of Alpha but is in a different package. If a class is both a subclass of and in the same package as the class with the protected method, then the class has access to the protected method. Public Now for the easiest access specifier--public. Any class, in any package, can call a class's public methods. To declare a public method, use the keyword public. For example,

Comments
  • This code does not produce this error. The method tryMeProtected() doesn't exist at all.
  • Did you test this with the exact code you posted? if yes it can not work as EJP saied, you have two different names: tryMePublic and tryMeProtected
  • outside or in the same package (both of course), not only outside
  • In the same package they are accessible through separate instance as it has same visibility as default in java (except for subclasses which can inherit even outside the package).
  • Yes, agreed, I would prefer a sentence like: "Inheritance of protected methods makes sense only with different packages." ;)
  • @Mik378 : Yes correct. I have modified the statement in the post. Thank you for pointing it out. :-)
  • @CloudyMarble Of course, but the essence of inheritance concept with protected keyword is about different packages. Otherwise, default packages scope would be enough. Of course: who can do more can do less