How can we define a method name same as class name in java

In Java, it is possible to define a method with the same name as the class itself. This type of method is called a constructor, and it is used to initialize objects of the class.

To define a constructor in Java, the method name must be the same as the class name. The constructor method does not have a return type, and its purpose is to allocate memory for an object of the class and to initialize its variables.

Here is an example of a constructor for a class named "Person":

 

public class Person {
  private String name;
  private int age;

  // Constructor method
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

In this example, the constructor method has the same name as the class name "Person". It takes two parameters, a String "name" and an integer "age", which are used to initialize the corresponding variables of the object.

It's important to note that a class can have multiple constructors with different parameters, allowing for different ways to create objects of the class. However, in each case, the constructor method must have the same name as the class.

Submit Your Programming Assignment Details