Deep_89
Deep_89

Reputation: 37

Does the object of superclass created when object of derived class is created?

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

Answers (4)

Stephen C
Stephen C

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

Johm Don
Johm Don

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

Balaswamy Vaddeman
Balaswamy Vaddeman

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

arya
arya

Reputation: 170

  1. yes, the object of super class is created.
  2. You cannot access the private members of your superclass or else they wont be private. you can have protected or public accessor methods in superclass and that could return the value of your private variables. OR, you could use reflection to access the private variables. But that you could use for anything, not only just superclass.

Upvotes: 0

Related Questions