• Post Reply Bookmark Topic Watch Topic
  • New Topic

inheritance and private access level modifier  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a problem regarding the behaviour of class members with private access level modifier:

Consider the code below:



This code compiles just fine with the expected output.

Inheritance provides the subclass access to superclass's members as if they were defined in the subclass itself,i.e. now the subclass owns the inherited class members exclusively.But as we know that those class members defined with 'private' access level modifier are not inherited.

Following what is stated above(I am assuming that its not wrong), in the code, class B must get his own copy of data member int b,GetValues() and SetValues() except for int a,which is correct.Now if class B does not own int a (as it fails 'b1.a' test), how come the SetValues() and GetValues() functions are able to access int a for a class B's object b1. Isn't it illogical as per the rules of java language?
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is why I think it's inaccurate to say that private members are not inherited. They are not visible to subclasses, but they still exist (as you have shown) and can be accessed indirectly.
 
Ranch Hand
Posts: 222
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To reinforce the statements made, the subclass includes all members of the superclass but but can't access members of the spuerclass that are declared private. I had problems with seeing the logic of this until I considered a practical example. in the following example the logic of the private access modifier leaves intact the original state of the height, width and depth objects which are used in different methods (for different purposes) ie: returning a Box specifying all dimensions, returning a box specifying no dimensions, returning a cube. Inheritance allows exposure through intermediate methods allowing manipulation of the superclass object for different purposes without altering its original state. Hope that helps


 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Subclass still has parent class's private members as its part, its only that it can't access them.
If that is not the case then it doesn't mean anything when we say that subclass inherits parent class's
behaviour because that behaviour may very well depend on those private members and if subclass doesn't
have those private members then how can it exhibit that particular behaviour.

Manish
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!