aspose file tools*
The moose likes Beginning Java and the fly likes Can you access inherited protected data members in another instance of the same class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can you access inherited protected data members in another instance of the same class?" Watch "Can you access inherited protected data members in another instance of the same class?" New topic
Author

Can you access inherited protected data members in another instance of the same class?

Nige Wheeler
Greenhorn

Joined: Feb 26, 2010
Posts: 3
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?

Any assistance appreciated!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

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;


[Jess in Action][AskingGoodQuestions]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
You can always access class members in another instance of the same class.

And welcome to the Ranch
Nige Wheeler
Greenhorn

Joined: Feb 26, 2010
Posts: 3
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!
 
wood burning stoves
 
subject: Can you access inherited protected data members in another instance of the same class?