HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java Constructors


-A constructor in Java is a special method that is called when an object of a class is created.

-It is used to initialize the object's data members.

-The constructor name must be the same as the class name, and it cannot have a return type

Types of Java constructors

There are two types of constructors in Java:


A constructor is called "Default Constructor" when it doesn't have any parameter.

Example
        
//Java Program to create and call a default constructor  
class Car{  
//creating a default constructor  
Car(){System.out.println("Car is created");}  
//main method  
public static void main(String args[]){  
//calling a default constructor  
Car b=new Car();  
}  
}
Output:
Car is created

-The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

A constructor which has a specific number of parameters is called a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.>

Example
   
//Java Program to demonstrate the use of the parameterized constructor.  
class Car1{  
    int id;  
    String name;  
    //creating a parameterized constructor  
    Car1(int i,String n){  
    id = i;  
    name = n;  
    }  
    //method to display the values  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    //creating objects and passing values  
    Car1 s1 = new Car1(444,"Honda");  
    Car1 s2 = new Car1(555,"Alto");  
    //calling method to display the values of object  
    s1.display();  
    s2.display();  
  }  
}

Output: 444 Honda 555 Alto

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

Example
public class Main {
  int x;

  public Main(int y) {
    x = y;
  }

  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println(myObj.x);
  }
}

// Outputs 5

You can have as many parameters as you want:

Example
public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

// Outputs 1969 Mustang