/* related posts with thumb nails */

Constructor:

1.

§ 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.

Example:

class Counter

{

private int count;

Counter() /* Constructor */

{

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

count=0;

}

}

class Test

{

public static void main(String as[])

{

Counter c1,c2;

c1 = new Counter();

c2 = new Counter();

}

}

Explanation:

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:

0 comments:

Post a Comment