/* related posts with thumb nails */



§ Constructor is a member function that takes the same name as that of the class and it is called automatically when the objects are created.

§ Constructor can take arguments.

§ Constructors can be overloaded i.e. we can have any number of constructers provided they take different number or types of arguments.

§ Constructors do not specify any return type, not even void. This is because they return the instance of the class itself.

§ Generally, constructors are used for initializing the data members or for memory allocations, but it allows any type of statements.


class Counter


private int count;

Counter() /* Constructor */


System.out.println( “initializing…”);




class Test


public static void main(String as[])


Counter c1,c2;

c1 = new Counter();

c2 = new Counter();




In the above example, there is a constructor “Counter()”, which has the same name as that of the class “Counter”. It is called automatically called for the objects “c1” and “c2” when they are instantiated. The “count” value for the objects c1 and c2 becomes “0”. The program also prints the message “initializing…” twice as we have created two objects.

Related Topics:


Post a Comment