DEV Community

Chithra Priya
Chithra Priya

Posted on

Constructor in Java:

Constructor:

Constructor is method used to initialize object specific values to variables. JVM have default constructor.

Why use constructor?

  • Each object gets initialized properly when it’s created.
  • Helps reduce code repetition.

Characteristics:

  1. Constructor name as same as class name.
  2. No return type required.
  3. Automatically called when object is created.
  4. Initialize object specific values to variable.

Types of Constructor:
1. Default Constructor:

  • A constructor with no parameters.
  • If you don’t write any constructor, Java provides one by default.

Program for Default Constructor:

class Car {
    Car() {
        System.out.println("Car is created");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); 
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Car is created

2. Argument Constructor:

  • Constructor that takes arguments to initialize the object with specific values.

Program for Argument Constructor:

public class Market
{
static String marketName = "Nehru";
String prodname;
int price;

public Market(String s, int i)
{
System.out.println("I'm constructor");
prodname = s;
price = i; 
}

public static void main(String[] args)
{
Market prod1 = new Market("abc",100);
Market prod2 = new Market("xyz",1000);
System.out.println(prod1.prodname);
System.out.println(prod2.prodname);
System.out.println(prod2.price);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:
I'm constructor
I'm constructor
abc
xyz
1000

Top comments (0)