DEV Community

Cover image for Constructor in Java
Harini
Harini

Posted on

Constructor in Java

What is a Constructor?
When we make an object of a class in Java, a special method called a constructor runs automatically. The main job of this is to set the initial values for the variables inside the object.

Important Points

  • The name of the constructor should be the same as the name of the class.
  • It doesn't have a return type, not even void.
  • Using constructor overloading, a class can have more than one constructor.
  • The constructor is called automatically every time you make an object.

Syntax

class Classname{
    Classname(){
        // constructor body
    }
}
Enter fullscreen mode Exit fullscreen mode

Example

public class Shop {

  public Shop() {
    System.out.println("Constructor");
  }

  public static void main(String[] args) {
    System.out.println("Main Method");

    Shop product = new Shop();
  }
}
Enter fullscreen mode Exit fullscreen mode

Types of Java Constructors

  1. Default Constructor
  2. No-Argument Constructor
  3. Parameterized Constructor

1. Default Constructor

Java will automatically give us a constructor if we don't make one ourselves. This is known as the default constructor. It doesn't need any parameters and sets the variables to their default values.

  • No arguments are needed.
  • Variables get default values like this:
    • int = 0
    • String is null and boolean is false.

Example

public class Shops {
    String name;
    int price;

    public static void main(String[] args) {
        Shops obj = new Shops();

        System.out.println(obj.name);   
        System.out.println(obj.price);  
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

2. No-Argument Constructor

A constructor with no parameters is called a no-argument constructor. We mostly use it when we want to give an object some set or pre-defined values when we make it.

Example

public class Shops {

    public Shops() {
        System.out.println("No-argument constructor");
    }

    public static void main(String[] args) {
        Shops product = new Shops();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

3. Parameterized Constructor

When we want to pass values while making an object, we use a parameterized constructor. Then, these values are used to set up the object's variables.

Example

public class Shops {
    String name;
    int price;

    public Shops(String str, int i) {
        name = str;
        price = i;
    }

    public static void main(String[] args) {

        Shops product1 = new Shops("Bag", 100);
        Shops product2 = new Shops("Note", 40);

        product1.display();
        product2.display();
    }

    public void display() {
        System.out.println(name + " " + price);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)