Forums Register Login
Inheritance, private fields
Hi guys!

Could you please help me with my concern about inheritance of private members. It is stated that: "A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass."

I don't understand why the private variable isn't inherited while you are able to access it using an inherited public method?

For example, we have two classes:

Now let's create two objects:

For both of these objects I can use:

So I can get private variable with bObj. So the variable is inherited, otherwise how did I get an access to it?

I realise that child object contains an object of parent class in it... so I'm just confused about the statement "a subclass doesn't inherit the private members of its parent class". Can you clarify this for me please?

Thank you!

They added this constraints to give the developer more options, if you are the author of class A and you don't want the subclass to access the local variables so you make it private, but if you want to pass these variable to specific classes you use the getter methods.
I hope i make sense.
Yes, this is clear, thank you. But what I meant is that why it is stated those private instance variables aren't inherited while you still can have an access to them using inherited public method. Let me ask it another way - where does this not inherited private instance variable "live"? Definitely it sholud "live" in an object of child class? If so - the private variable is inherited.
These methods just let you read the variables which are private in the superclass. hence, these variables are not part of the subclass, as you can't re-assign values to them for example!
hi ,

private member not inherited that means you are not able to access those variable directly by the object of child class.
But still they are living inside of child object, right?
I just debugged your code, within the LIVE objects is the object.getA() and it has value of "a". That means the live object is the method!
you can say that 'they are living inside of child object' because child object has the only reference of public or protected variable or function of base class in that function you can have the reference of private member of base class.
Hey,Rahul.Welcome to JavaRanch
Well, it seems like clear, thank you guys.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards

All times above are in ranch (not your local) time.
The current ranch time is
Oct 20, 2017 02:41:19.