Reputation: 37
If I have a class C which inherits class B and class B inherits class A, then If I create an object of Class C, is the object of superclasses created?? If yes, how?? How to access the private members of class A??
Upvotes: 0
Views: 444
Reputation: 719606
Does the object of superclass created when object of derived class is created?
No.
The superclass constructor is used to initialize the superclass-defined state of the currebt object, but this does NOT amount to creating an instance of the superclass.
If I have a class C which inherits class B and class B inherits class A, then If I create an object of Class C, is the object of superclass created??
No. See above.
If you create an instance of C, you will have one object whose most-derived type is C. This object will also be an instanceof
B, but it may not behave exactly like a regular B due to method overriding in C and other things.
If yes, how??
Moot.
How to access the private members of class A??
You cannot directly access the private
members of a superclass from a subclass. That is what the private
access modifier means. If you need to access them you need to use them, you either need to create non-private methods in the superclass to do this (e.g. getters and/or setters), or change the members' access.
(An alternative is to use reflection to override the private
access modifiers, but you should only use that as a last resort. It is better to fix the superclass code to provide the required access ... or figure out away that the subclass doesn't need access at all.)
Upvotes: 1
Reputation: 639
It depends on what language you are using. If you are using C++, you may be able to make the sub-class a friend of the super-class and then you could access its public members. If you you use Java, you could use reflection to locate the super object and reflect on that, but it would be more trouble than it would be worth.
Upvotes: 0
Reputation: 8540
you can not access private variables outside of the class.
to access them,
1. you may make them public or protected but it is not a good idea.
2. you can write getter method for it which is again not a private method,It is good approach.
3. you may use reflection to access it.
provide more information to help you better
Upvotes: 0
Reputation: 170
Upvotes: 0