aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private variables inherited but not accessible Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private variables inherited but not accessible" Watch "Private variables inherited but not accessible" New topic
Author

Private variables inherited but not accessible

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Hi All,
The JLS states that..

JLS 6.6.8
A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited by subclasses

But I dont quite agree with this. According to me, private variables are inherited by the subclasses, but NOT accessible.

Any thoughts? Thanks.
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
JLS Chapter 8.2.1.3 Inheritance with private


the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs because method move of class Point3d tries to increment totalMoves.

[ November 13, 2003: Message edited by: Vad Fogel ]
Arulkumar Gopalan
Ranch Hand

Joined: Oct 13, 2003
Posts: 104
But I dont quite agree with this. According to me, private variables are inherited by the subclasses, but NOT accessible
new Private().getI();

Hi Cathy,
Actually in this piece of code we are accessing super class' variable through it's own objects. Definitely this is not inheritance.
So, i think it is in the reverse way. Private variables are NOT inherited by the subclasses, but can be accessible through instances.(i mean through the instance of class where the variable is declared).
[ November 13, 2003: Message edited by: Arul kumar ]

Anbudan & Mahalo,<br />Arul<br /> <br />-Not a sun certified Java professional :-)
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Cathy,
In that code sample, you're not really accessing teh private variable directly. Rather, you're using an inherited method to access a private variable. Try it like this and I think you'll find it less confusing:

I haven't compiled this myself but, assuming I didn't have any typos, you should get a compiler error when you try to compile this. Why? Because in the Lower class, you're trying to access a variable named x which doesn't exist in class Lower. It was defined in class Upper, but it doesn't get inherited.
Next, try removing the output of the variable x and leave in the output of the variable y. This works fine. Why? Because y is a public variable defined in the superclass - it IS inherited.
I hope that helps.


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Private variables inherited but not accessible