DEV Community

mohandass
mohandass

Posted on

Constructor Method in Java

  • A constructor in Java is a special block of code—similar to a method—that is automatically called when an instance (object) of a class is created. Its primary purpose is to initialize the state or attributes of the newly created object.

Rule For Creating Constructor

  • The constructor name must match the class name precisely.

  • No Return Type It cannot have a return type, not even void.

  • It is implicitly triggered by the new keyword during instantiation.

Types of Constructor

1. Default (No-Argument) Constructor:

  • If you do not write any constructor in your class, the Java compiler automatically inserts an implicit no-argument default constructor.

  • It sets primitive variables to their defaults (e.g., 0, false) and object references to null. You can also write your own explicit no-arg constructor.

public static void main(String[] args)
{

Car model = new Car();{
System.out.println("No-Argument Constructor")
}
Enter fullscreen mode Exit fullscreen mode

2.Parameterized Constructor

  • This type accepts arguments, allowing you to assign unique, custom values to an object's properties right at the moment of creation.
public Car(String name,int price,String color)
{

this.name = name;
this.price = price;
this.color = color;
}
Enter fullscreen mode Exit fullscreen mode

3. Constructor Overloading

  • Java allows you to define multiple constructors in single class provided they have different parameters lists(we can use different number of parameters and different data types)

  • The compiler detects which one to run based on the values passed.

Overall Example


public class Car{

String name;
int price;
String color;

public Car(){

System.out.println("No-Argument Constructor");

}


public static void main(String[] args)
{

    //Explicit No-Argument Constructor
Car model = new Car();


    // Parameterized Constructor
Car model1 = new Car("Tata punch" , 500000,"gray");
Car model2 = new Car("Tata Nexon", 700000,"white");


   //Overloaded constructor
Car model3 = new Car("Tata Safari",1300000,"red");


System.out.println("CarName :" + model1.name);
System.out.println("Price :" + model1.price);
System.out.println("Color :" + model1.color);

System.out.println("CarName :" + model2.name);
System.out.println("Price :" + model2.price);
System.out.println("Color :" + model2.color);

System.out.println("CarName :" + model3.name);
System.out.println("Price :" + model3.price);
System.out.println("Color :" + model3.color);
}
public Car(String name,int price,String color)
{

this.name = name;
this.price = price;
this.color = color;
}

}


Enter fullscreen mode Exit fullscreen mode

OUTPUT :

REFERENCE :

https://www.geeksforgeeks.org/java/constructor-overloading-java/

Top comments (0)