Constructors are the methods having the same name as that of the class and are automatically executed on defining an object. The main purpose of a constructor is to initialize a new object.
Java does not allocates memory for objects at application startup time but rather when the instance is created by keyword new. When new is invoked, Java allocates enough memory to hold the object and then initializes any instance variables to default values.
Constructors are of two types:
1. Default constructor
2. Parameterized constructor
A constructor that takes no arguments, is the default constructor. If a class does not explicitly define any constructors at all, Java automatically provides a no-argument constructor that does nothing. Thus all classes have at least one constructor.
A constructor in which certain parameters are sent to initialize the instance variables, we call it a parameterized constructor.
class Rectangle { int l,b,a; Rectangle() { l=135; b=12; } void GetData() { a=l*b; System.out.println("Area of Rectangle is : "+a); } } class RectangleDefaultConstructor { public static void main(String args[]) { Rectangle Rect = new Rectangle(); Rect.GetData(); } }