+ 1

Can someone please explain this to me? "the constructor of the superclass is called when the subclass is instantiated.".

How can the subclass be instantiated?

13th Feb 2017, 2:35 PM
Ziad Hassan Ahmed
Ziad Hassan Ahmed - avatar
8 odpowiedzi
+ 19
If you want to call the constructor of the superclass you must create an instance of the superclass or subclass. The constructor is called only once when the instance is created. You can't call it like a member function.
13th Feb 2017, 2:59 PM
Igor Makarsky
Igor Makarsky - avatar
+ 17
The subclass is instantiated when you use the "new" keyword. For example: Car car = new Car();
13th Feb 2017, 2:43 PM
Igor Makarsky
Igor Makarsky - avatar
+ 4
When you construct the extended class with MyExtendedClass mec = new MyExtendedClass(); the constructor of the extended class is called. And in that constructor the constructor of the parent class is always called by super (); as the first command. You can write that command, but you don't have to. It is always executed no matter if you wrote it down or not.
13th Feb 2017, 3:43 PM
Tashi N
Tashi N - avatar
+ 2
I'm confused because at first they said "Constructors are not member methods, and so are not inherited by subclasses" and then said "however, the constructor of the superclass is called when the subclass is instantiated." and I don't understand the deference between the two cases..
13th Feb 2017, 2:49 PM
Ziad Hassan Ahmed
Ziad Hassan Ahmed - avatar
+ 1
Thanks a lot, Tashi and K. C. Leung. 😊
13th Feb 2017, 11:02 PM
Ziad Hassan Ahmed
Ziad Hassan Ahmed - avatar
0
But couldn't be done another way?
13th Feb 2017, 2:46 PM
Ziad Hassan Ahmed
Ziad Hassan Ahmed - avatar
0
Thanks a lot, Igor makarsky. 😊
13th Feb 2017, 10:57 PM
Ziad Hassan Ahmed
Ziad Hassan Ahmed - avatar