Issue
I have gone through so many websites which explains about access specifiers in java such as java papers, rel="noreferrer">java's access specifiers, and many other stackoverflow questions like here.
All these guys explained that the protected member can be accessed by any subclass(also by the subclass out of package) and can be accessed by the package level classes.
While experimenting on protected members, I found out that I'm unable to access a protected member from a subclass outside package.
Check the code below. A public class with protected members:
package com.One;
public class ProVars {
protected int i = 900;
protected void foo()
{
System.out.println("foo");
}
}
Another public class in different package trying to access protected member:
package com.Two;
import com.One.ProVars;
public class AnotherClass extends ProVars {
public static void main(String[] args) {
ProVars p = new ProVars();
System.out.println(p.i);//the field ProVars.i is not visible(Compilation Error)
p.foo();//the method foo() from the type ProVars is not visible
}
}
Any explanation is appreciated.
Solution
You're attempting to use them as if they were public
. They are not public
, they are protected
.
Example
ProVars p = new ProVars();
p.foo(); // This will throw an error because foo() is not public.
The correct usage, for a subclass to use a protected
method or variable is:
public class MyClass extends ProVars
{
public MyClass()
{
System.out.println(i); // I can access it like this.
foo(); // And this.
}
}
Why does this work?
Because you've inherited
the class. That means you've got all of its methods and it's variables. Now, because your method and variable is protected
, it also means that it can be accessed from the subclass
. Try and declare them as private
and see what happens.
Answered By - christopher
Answer Checked By - Robin (JavaFixing Admin)