DEV Community

Kavitha
Kavitha

Posted on

How to Achieve a Constructor in Java?

How to Achieve a Constructor in Java?
You can achieve a constructor by:

  • Creating a class
  • Writing a method with the same name as the class
  • Using the new keyword to call it when creating an object

Step-by-Step Example
Step 1: Create a Class
Step 2: Define a Constructor
Step 3: Create an Object to Call the Constructor

class Student {

    int rollNo;
    String name;

    // Constructor
    Student(int rollNo, String name) {
        this.rollNo = rollNo;
        this.name = name;
    }

    void display() {
        System.out.println(rollNo + " " + name);
    }

    public static void main(String[] args) {
        Student s1 = new Student(1, "Kavitha"); // Constructor called
        s1.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

How Constructor is Achieved Here

  • The constructor is created using the same name as the class
  • It initializes object values
  • It is automatically called when creating object
new Student(1, "Kavitha");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)