How Constructor Works?

How Constructor Works??

  
As I told u previously constructor is called when the object of a class is created. When we create an object of a class, it calls not only the constructor of its own class but also the class it extends.
Here is an example to show the working of a constructor.
 
Firstly there is a class with the name Hello2.
  1. public class Hello2 {  
  2.  public Hello2() {  
  3.   System.out.println("Hello2");  
  4.  }  
  5. }  
Now another class Hello1 extends the Hello2  class and we create the object of Hello1 to see which constructor this object calls.
 
public class Hello1 extends Hello2
  1. {  
  2.  public Hello1() {  
  3.   System.out.println("hello1");  
  4.  }  
  5.  public static void main(String[] args) {  
  6.   Hello1 h = new Hello1();  
  7.  }  
  8. }  
When you run the Hello1.java ,you will get the output as:-
 
Hello2
 
hello1
 
So, as you see Hello1 class object first call the constructor of the class it extends and then call the constructor of its own class.
 
Note 
By default, all classes in java extends the Object class, so if a class don't extend any class then the constructor of object class runs.