Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private variables inherited but not accessible

 
Cathy Song
Ranch Hand
Posts: 270
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 104
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic