DEV Community

Pavithraarunachalam
Pavithraarunachalam

Posted on

Constructor in Java..

Constructor:

  • In Java, a constructor is a special method used to initialize objects. It's called when an object of a class is created.

  • In constructor JVM is the default constructor.

What is the uses of constructor?

  • constructors are special methods used to initialize objects when they are created. They have the same name as the class and no return type (not even void).

Characteristics:

  • A constructor must have the same name as the class in which it is declared.

  • Constructors do not have a return type, not even void.

  • A constructor is automatically invoked when an object is created.

  • Java allows constructor overloading—you can define multiple constructors with different parameter lists.

Types of constructors:

1. Default constructor in java:

  • In default constructor they will not provide an arguments, provided by Java if no other constructor is defined.

Default constructor Example:

class Car {
       Car() {
        System.out.println("This is a car.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();  

    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

This is a car.

Enter fullscreen mode Exit fullscreen mode

Arguments constructor in java:

  • Constructor arguments are values you pass to a constructor when you create an object.These arguments helps initialize the objects with specific values.

Argument constructor Example:

public class Market
{
static String marketName = "Pragyaa";
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",2000);
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
2000

Enter fullscreen mode Exit fullscreen mode

Top comments (0)