Wednesday, January 20, 2016

Topic 12: Constructors in Java

It can be tedious to initialize all of the variables in a class each time an instance is created. It would be simpler and more concise to have all of the setup done at the time the object is first created. This automatic initialization is performed through the use of a constructor. 

  • A constructor initializes an object immediately upon creation

  • It has the same name as the class in which it resides and is syntactically similar to a method

  • Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. 

  • Constructors do not have return type, not even void. This is because the implicit return type of a constructor is the class type itself. 


/* Box uses a constructor to initialize the dimensions of a box. */
class Box
{

double width, height, depth;

// This is the constructor for Box.
Box()
{
width = height = depth = 10;
}

double volume()
{
return width * height * depth;
}
}

class BoxDemo6
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();

System.out.println("Volume is " + mybox1.volume());
System.out.println("Volume is " + mybox2.volume());
}
}

When we allocate an object, we use the following general form: class-var = new classname( );

The parentheses are needed after the class name because in actuality we are calling constructor for the class. When we do not explicitly define a constructor for a class, then Java creates a default constructor for the class. The default constructor automatically initializes all instance variables to zero.


Parameterized Constructors

Constructors like normal methods can be parameterized. The following version of Box defines a parameterized constructor that sets the dimensions of a box as specified by those parameters. Pay special attention to how Box objects are created.

// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}


//Inside main, objects are created
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9); 

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment