An object will require form of initialization when it is created. To accommodate this, java allows you to define constructors for classes.
A constructor is a special method that creates and initializes an object of a particular class. It has the same name as its class and may accept arguments.
It is similar to any other method. It does not have a return type. But it returns a reference to the object that it creates. If you do not explicitly declare a constructor for a class, the java compiler automatically generates a default constructor that has no arguments.
A constructor is never called directly. It is invoked by the new operator.
Syntax of Constructor
className(cparam)
{
// body of constructor
}
Example of Constructor
Example 1 : Program to create a class Square having height and width variables and constructor which assigns default values to variables
class Square
{
int height;
int width;
Square()
{
height = 0;
width = 0;
}
}
class ImplSquare
{
public static void main(String args[])
{
Square sObj = new Square();
System.out.println("Object height = " + sObj.height);
System.out.println("Object width = " + sObj.width);
}
}
Output
Object height = 0
Object width = 0