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();
?
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.
If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected.
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only.
Yes, the protected method of a superclass can be overridden by a subclass.
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.
I believe you misunderstand the difference between package
and protected
visibility.
package package1;
public class MyClass1 {
public void tryMePublic() { System.out.println("I'm public"); }
protected void tryMeProtected() { System.out.println("I'm protected"); }
void tryMePackage() { System.out.println("I'm package"); }
}
tryMePublic
will be accessible wherever you are.tryMeProtected
will be accessible to every subclass AND every class in the same package.tryMePackage
will be accessible to every class in the same package (not available in children class if they are in a different package)package package1;
public class Class2 extends MyClass1 {
public void doNow() {
tryMePublic(); // OK
tryMeProtected(); // OK
tryMePackage(); // OK
}
}
package package2;
import package1.MyClass1;
public class Class3 extends MyClass1 {
public void doNow() {
MyClass1 c = new MyClass1();
c.tryMeProtected() // ERROR, because only public methods are allowed to be called on class instance, whereever you are
tryMePublic(); // OK
tryMeProtected(); // OK
tryMePackage(); // ERROR
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With