Constructor in Java

Constructor In Java

Constructor is a special method that is used to initialize objects in Java. It is called when we create the object of a class. It can be used to set initial values for objects.

Rules For Creating Java Constructor

  • Constructor name must be the same as its class name.
  • Constructor does not have any return type.
  • Constructors are only called once at object creation.

Example

class Computer{
    // properties
    int id;
    String name;
    double price;

    // constructor
    public Computer(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    // methods
    void printDetails(){
        System.out.println("ID is "+this.id);
        System.out.println("Name is "+this.name);
        System.out.println("Price is "+this.price);
    }

}
// Main class
public class Main {
    // main method
    public static void main(String[] args) {
        //Creating a object from class Computer. We must give parameter value here
        Computer com1 = new Computer(1, "MSI",233.0);
        // Assign value to class properties
        System.out.println(com1.id);
        System.out.println(com1.name);
        System.out.println(com1.price);
    }
}

Constructor Overloading In Java

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. The compiler differentiates them by the number of parameters in the list and their types.

Example

class Computer{
    // properties
    int id;
    String name;
    double price;

    // constructor
    public Computer(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    public Computer(int id, String name) {
        this.id = id;
        this.name = name;
        this.price = 0;
    }
    // methods
    void printDetails(){
        System.out.println("ID is "+this.id);
        System.out.println("Name is "+this.name);
        System.out.println("Price is "+this.price);
    }

}
// Main class
public class Main {
    // main method
    public static void main(String[] args) {
        //Creating a object from class Computer. We must give parameter value here
        Computer com1 = new Computer(1, "MSI",233.0);
        // Assign value to class properties
       com1.printDetails();
    }
}
Show Output