Home >Java >javaTutorial >Why is the name of the constructor in Java the same as the class name?

Why is the name of the constructor in Java the same as the class name?

王林
王林forward
2023-08-26 21:13:161021browse

Why is the name of the constructor in Java the same as the class name?

Every class object is created using the same new keyword, so it must have information about the class in which the object must be created. Therefore, the name of the constructor should be the same as the class name.

Example

class MyConstructor{
   public MyConstructor() {
      System.out.println("The constructor name should be same as the class name");
   }
   public static void main(String args[]){
      MyConstructor mc = new MyConstructor();
   }
}

In the above program, the name of the constructor should be the same as the class name (MyConstructor).

Output

The constructor name should be same as the class name

The above is the detailed content of Why is the name of the constructor in Java the same as the class name?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete