In java, there's three levels of access:
- Public - Open to the world
- Private - Open only to the class
- Protected - Open only to the class and its subclasses (inheritance).
So why does the java compiler allow this to happen?
TestBlah.java:
public class TestBlah {
public static void main(String[] args) {
Blah a = new Blah("Blah");
Bloo b = new Bloo("Bloo");
System.out.println(a.getMessage());
System.out.println(b.getMessage()); //Works
System.out.println(a.testing);
System.out.println(b.testing); //Works
}
}
Blah.java:
public class Blah {
protected String message;
public Blah(String msg) {
this.message = msg;
}
protected String getMessage(){
return(this.message);
}
}
Bloo.java:
public class Bloo extends Blah {
public Bloo(String testing) {
super(testing);
}
}
Because protected means subclass or other classes in the same package.
And there's actually a fourth "default" level of access, when the modifier is omitted, which provides access to other classes in the same package.
So
protected
is between default andpublic
access.There are actually four levels of access: "public", "protected", "private" & default also known as package private or package protected. Default limits accessibility to the package. Default is quite useful and I use it frequently.
You're able to call
b.getMessage()
becauseb
is of typeBloo
, which extendsBlah
, andgetMessage()
is protected. Protected, as you mentioned, allows subclasses to access the method.You've got the following errors, though:
super()
with no arguments in theBloo
constructor is an error. The compiler can't find the no-parameterBlah
constructor because you defined one with a String parameter.new Blah()
inTestBlah
main
method is an error for the same reason as above.a.testing
andb.testing
is an error because you didn't define the variabletesting
for any class.Actually it should be:
That's why
To be more specific, you're expecting
protected
to work as it does in C++.However, in Java, it has a different meaning. In Java, a protected method is available to the class (obviously), all the other classes in the same package and any subclasses of this class. Classes in other packages will not have access unless they subclass this original class.
See this similar question for more specific information on inheritance markers.
Personally, I almost never use
protected
. I develop applications rather than frameworks so I'm much more likely to definepublic
methods,private
data and, quite often, mark my whole class asfinal
.