This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am using the Sybex SCJP book to study for the 1.5 exam. Last night I did one of their mock exams on the CD and got a question wrong because, so the answer said, you "cannot access protected superclass data of a different instance".
The specific context was a class a.X extends b.Y, and b.Y has a protected instance variable called 'size'. The question asked if you could use the expression new X().size within X's class definition. Note that 'size' was not itself redeclared within the class definition so it was available to X only through inheritance. I said yes, but the answer said no.
I have since checked this within Eclipse and it seems that you CAN use the expression. Can anyone confirm exactly what the rule is here? Probably more importantly, I guess the Sybex book was trying to make a point here and although they have made it inaccurately can anyone suggest exactly what point they might have been trying to make?
They might have tried (and failed) to explain that if c.Z is another class that extends b.Y, then code in a.X cannot access "size" in an instance of c.Z, or, more generally, any instance of b.Y that is not known at compile time to be a.X -- i.e., this is illegal
// Code is in a.X
b.Y parent = new a.X();
int illegal = parent.size;
You can always access class members in another instance of the same class.
And welcome to the Ranch
Joined: Feb 26, 2010
Thanks Ernest and Campbell for your help. Worrying that the book makes such a fundamentally incorrect statement, but at least it was the author that was wrong rather than me so I must have been doing something right in my studies! Maybe I'll see if Sybex has a way to report errata like this.
Looking forward to more discussions like this on the ranch. Even though I only joined yesterday I can already see what a great site it is. Yeehah!