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 name Hello2.

public class Hello2

{

    public Hello2()

    {

        System.out.println("Hello2");

     }

 }


Now another class Hello1 extends the Hello2  class and we create the object of Hello1 to see which constructor this objects calls.
 

public class Hello1 extends Hello2

{

   public Hello1()

   {

      System.out.println("hello1");

    }

    /*** @param args*/

    public static void main(String[] args)

    {

          // TODO Auto-generated method stub

          Hello1 h=new Hello1();

    }

  }

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.
 

Ebook Download
View all
Learn
View all