DEV Community

Ligouri S Tittus
Ligouri S Tittus

Posted on

Constructor in java

*What is constructor ?
*

In Java, a constructor is a special method that is used to initialize objects when they are created.
The constructor is called when an object of a class is created.
A constructor in Java is similar to a method.
The Java compiler
provides a default
constructor if you don't
have any constructor in a
class.

Rules for creating Java constructor:
There are two rules defned for the constructor.

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type

Types of Java constructors

There are two types of constructors in Java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Example for constructor:

class Student {
    String name;
    int age;

    // parameterized constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 20);
        System.out.println(s1.name + " " + s1.age);
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)