Constructor is a special method in Java which is used to initialize the object. It looks like a normal method however it is not. A normal java method will have return type whereas the constructor will not have an explicit return type. A constructor will be called during the time of object creation (i.e) when we use new keyword follow by class name.
For Example : Lets say we have class by the name “Test“, we will create object for Test class like below
Test t = new Test();
This will invoke the default constructor of the Test class.
Rules for creating a Constructors in Java
There are two important rules which has to be kept in mind before creating a constructor.
- A Constructor name should be the same name as the class name.
Suppose if we have class Test, Then constructors name also should be “Test” and not anything else.
- A Constructor cannot have a explicit return type
We cannot declare a constructor with return type. For example we cannot have constructor like public void Test()
Types of Java Constructors
There are two type of Constructors in Java, they are
- Default Constructor (or) no-arg Constructor
- Parameterized Constructor
Default Constructor (or) no-arg constructor
A Constructor with no parameters is called as Default Constructor or no-arg constructor. In the below code we have created the no-arg constructor which gets called during the time of object creation (Car c = new Car())
public class Car { Car() { System.out.println("Default Constructor of Car class called"); } public static void main(String args[]) { //Calling the default constructor Car c = new Car(); } }
Output :
Default Constructor of Car class called
Parameterized Constructor
A Constructor which has parameters in it called as Parameterized Constructors, the Parameterized constructor is used to assign different values for the different objects. In the below example we have a parameterized constructor for the car class which set the value for the parameter “carColor”
public class Car { String carColor; Car(String carColor) { this.carColor = carColor; } public void disp() { System.out.println("Color of the Car is : "+carColor); } public static void main(String args[]) { //Calling the parameterized constructor Car c = new Car("Blue"); c.disp(); } }
Output :
Color of the Car is : Blue
Can a Constructor return any value ?
The answer is the Constructor cannot return any explicit value but implicitly it will be returning the instance of the class.
public class Car { Car() { System.out.println("Default Constructor of Car class called"); } public static void main(String args[]) { //Calling the default constructor Car c1 = new Car(); } }
Here we doesn’t have any explicit return type but when you instantiate the class with the syntax
Car c1 = new Car();
We are actually creating new object by allocating memory and calling the constructor. Here, the result is clearly an instance of Class Car.
Leave a Reply