Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}

Out put :
Base Constructor Called
Derived Constructor Called

What I have tried:

My query is like this :

When the Derived class constructor is called the first statement to be printed is "Derived Constructor called" . But the first statement in the output is "Base Constructor Called.

Can anyone explain this
Posted
Updated 1-Aug-19 21:39pm

1 solution

When you create an object the system always calls the base constructor (if it exists) before any derived constructors, so that the base object is fully constructed and read for use before any add-on code tries to use it.

Think of it like this: if the base class was not constructed first, then the derived class couldn't use anything in it inside the constructor because it wouldn't have been built yet!
Suppose you have a base Label control which sets up the text to be "Arial, 12pt, Black", and you create a derived control called RedLabel which wants "Arial, 10pt, Red". If the derived constructor was called first, it's changes to the Font of the base control would be overwritten by the base constructor code and it would remain black and 12pt.
 
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