I am learning Java using the book Java: The Complete Reference. I am currently at chapter 9 and thus just inroduced to packages. On page 187, it says "If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected ". What I understand from this is, A subclass that resides in a package, say 'B', and extending a class that is defined as public inside another package 'A', having a member named "proc", then in order to make proc available in all subclasses, including subclasses defined outside the current package 'A', I have to mark it as protected. Now have a look at my implementation of the subclass defined inside package 'B':
package subapp;
import app.*;
public class Test extends App {
public Test() {
App app = new App();
System.out.println(app.proc); // error
}
}
I am sure that all the packages (in both the class files) are loaded correctly, "direct" superclass of Test and its non-parameterized constructor, are publicly accessible, proc is marked as protected, and the main() function has no problem there. But I get a runtime exception when running subapp.Test that says "proc has protected access in /superclass path/. Am I getting the book statement wrong or the statement itself is wrong?
You are already extending App, so you do not want to create a new App within the constructor. Instead, try something like this if the variable is protected
.
public Test() {
System.out.println(this.proc);
}
The reason it isn't working for you right now is you are making a new App
within the constructor, and then trying to access that App
's proc
value directly, instead of through inheritance.
If the proc
value is not correct through this, you might have to set it before the System.out.println(this.proc);
Or you could call the super();
constructor before printing the value if the proc
is getting initialized the the App
constructor, such as:
public App() {
proc = "test";
}
//.....
public Test() {
super();
System.out.println(this.proc);
}