Java Constructor
A constructor is a special member method for automatic initialization of an object.
A constructor executed automatically whenever an object is created. And you have to provide the constructor name as same as the class name. It is a kind of member method and initializes an instance of the class. It has the same name as the class name and no return value.
The constructor can have any number of the parameters of the class may have a number of constructors overloaded.
Rules for Constructor:-
- The constructor name must be the same as the class name.
- It has no return type.

Syntax:
class class_name
{
data_type member_data;
member method();
class_name() // constructor
{
.........
}
}
Types of Constructor
- Default constructor
- Parameterized constructor
Default Constructor
A Constructor having no arguments is known as the Default constructor. The default constructor is invoked at the time of the creation.
Example:
class Rectangle
{
int length=5,breadth=6;
float area;
Rectangle() //constructor
{
System.out.println("Enter the length and breadth value: "+length+" "+breadth);
area= length * breadth;
System.out.println("Area of the Rectangle: "+area);
}
}
public class Defaultconstructor
{
public static void main(String args[]){
Rectangle r1=new Rectangle();
}
}
Parameterized Constructor
Constructor having the parameters(arguments) is known as the Parameterized constructor. Parameterized constructor is used to provide different values to the various objects.
Example:
class Rectangle
{
int length,breadth;
float area;
Rectangle(int length,int breadth) //parameterized constructor
{
System.out.println("Enter the length and breadth value: "+length+" "+breadth);
area= length * breadth;
System.out.println("Area of the Rectangle: "+area);
}
}
public class Parameterizedconstructor
{
public static void main(String args[]){
Rectangle r1=new Rectangle(5,6);
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com