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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.