This question already has an answer here:
It seems very silly, but I am really confused. Please see below code:
package com.one;
public class SuperClass {
protected void fun() {
System.out.println("base fun");
}
}
----
package com.two;
import com.one.SuperClass;
public class SubClass extends SuperClass{
public void foo() {
SuperClass s = new SuperClass();
s.fun(); // Error Msg: Change visibility of fun() to public
}
}
I have read from oracle doc and here as well, that protected members are visible in the sub class in another package also. So fun() should be visible in SubClass in package two. Then why the error?
Am I terribly missing something very obvious?
The Java Language Specification says
What that means is that if you're writing a subclass outside the package of the original class, each object can call the superclass's protected methods on itself, but not on other objects.
In your example, because
s
is a different object fromthis
, you can't calls.fun()
. But the object would be able to call thefun
method on itself - withthis.fun()
or justfun()
.Protected methods are only visible to subclasses from the inside. If you create a new instance of
SuperClass
, you are accessing it from the outside.