java constructor method must meet the following syntax rules:
(1) The method name must be the same as the class name.
(2) Do not declare the return type.
(3) cannot be modified by static, final, synchronized, abstract and native. The constructor cannot be inherited by subclasses, so it is meaningless to modify it with final and abstract.
The constructor is used to initialize a new object, so it is meaningless to modify it with static. Multiple threads will not create the same object with the same memory address at the same time, so there is no need to modify it with synchronized.
In addition, the Java language does not support native type constructors.
Example:
public class Sample { private int x; public Sample() { // 不带参数的构造方法 this(1); } public Sample(int x) { //带参数的构造方法 this.x=x; } public int Sample(int x) { //不是构造方法 return x++; } }
The above is the detailed content of How to write java constructor method. For more information, please follow other related articles on the PHP Chinese website!