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?

王林
Release: 2023-08-26 21:13:16
forward
1071 people have browsed it

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();
   }
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template