DEV Community

Udaya M
Udaya M

Posted on

Constructor in Java:

Constructor:

Constructor is a special method used to initialize objects. It is called automatically When a object of a class is created.

Characteristics:

  1. Constructor name must be same as class name
  2. It has no return type not even void
  3. It is automatically invoked when the object is created.
  4. Can be overloaded i.e multiple constructors in one class with different parameters.

Types of constructors:

           Two Types of Constructors 
Enter fullscreen mode Exit fullscreen mode

1.Default Constructor

     A Constructor with no parameters.
     Provided automatically by the constructor if no constructor is written.
Enter fullscreen mode Exit fullscreen mode

Program For Defult:

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

  public static void main(String[] args) {
    Vehicle  v = new Vehicle();  // Constructor is called
  }
}
Enter fullscreen mode Exit fullscreen mode

output:
car is created.

Parameterised Constructor:

Constructor that accepts arguments to initialize the object with custom values.

Program for Parametersized:

class Student {
  String name;
  int age;
  Student(String n, int a) {
    name = n;
    age = a;
  }
void display() {
    System.out.println(name + " " + age);
  }

  public static void main(String[] args) {
    Student s1 = new Student("Ram", 20);
    s1.display();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Ram 20

Top comments (0)