Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When a sub class inherents a super class it intherents the protected/public
Attributes/methods , so i get why we call the super constructor in the sub constructor to initialize the attributes inherited.
But if the attributes in the super class were private they won’t be inherited so i don't get why we should call the super constructor inside the sub constructor to initialize them?

What I have tried:

The code implementation was 
Super class with private attributes 
sub class
The sub class constructor calls the super class constructor that initialize the private attributes in super class
So i tried to execute  the code without calling the super constructor in sub constructor and it didnt work out
Posted
Updated 24-Feb-22 5:49am
Comments
Richard MacCutchan 24-Feb-22 9:34am    
You need to do that in case the sub class later calls a method of the super class that relies on values that were initialised in the constructor. And as you discovered, ignoring the rules has consequences.
Deema 2022 24-Feb-22 9:41am    
Thanks!

1 solution

Think about it: all cars have a private glovebox: unless you are the owner of the car you have no idea what is in it.

But that doesn't stop the driver opening it and putting his mobile in there, or grabbing a face mask!

If A is the base class for B, it's constructor needs to be completed before the constructor for B can get going - otherwise the B class constructor might access properties or methods in A which use private fields or methods which haven't been set up yet.

So when you create an instance of B, the system automatically calls the base class A constructor first, and then calls the derived B class constructor once the base information is fully set up.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900