Constructors in java

Constructors

A constructor can be thought of as a specialized method of a class that creates (instantiates) an instance of the class and performs any initialization tasks needed for that instantiation. The sytnax for a constructor is similar but not identical to a normal method. It follows the rules mentioned below

The name of the constructor must be exactly the same as the class it is in.

Constructors may be private, protected or public.

A constructor cannot have a return type (even void). This is what distinguishes a constructor from a method.

Multiple constructors may exist, but they must have different signatures, i.e. different numbers and/or types of input parameters.

Default constructor: If you don't define a constructor for a class, a default parameter less constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).

The existence of any programmer-defined constructor will eliminate the automatically generated, no parameter, default constructor. If part of your code requires a  parameterized constructor and you wish to add it, be sure to add a no-parameter constructor.

Example:

class Rectangle

{

double length,bre;

Rectangle() // Constructor with no argument

{

length=bre=0;

}

Rectangle(double l) /* Constructor 1 */

{

length=bre=l;

System.out.println("Constructor 1 called");

}

Rectangle(double l,double b) /* Constructor 2 */

{

length=l;

bre=b;

System.out.println("Constructor 2 called");

}

void area()

{

System.out.println("\nArea of the Given rectangle");

System.out.println("Length  ="+length);

System.out.println("Breadth ="+bre);

System.out.println("Area   ="+(length*bre));

}

}

/* Main class  */

class construct

{

       public static void main(String args[])

      {

  Rectangle r1,r2;

System.out.println("Creating the object r1");

r1=new Rectangle(6); //Uses constructor 1

System.out.println("Creating the object r1");

r2=new Rectangle(2.5,3.0); //Uses constructor 2

r1.area(); //Calling method

r2.area();

      }

}


Output:

D:\java>javac construct.java

D:\java>java construct

Creating the object r1

Constructor 1 called

Creating the object r1

Constructor 2 called

Area of the Given rectangle

Length  =6.0

Breadth =6.0

Area   =36.0

Area of the Given rectangle

Length  =2.5

Breadth =3.0

Area   =7.5

D:\java>

Comments

Popular posts from this blog

History of C language

Lab programs of C

Algorithm Pseudopods Flow-chat