Home  >  Article  >  Java  >  How to write java constructor method

How to write java constructor method

藏色散人
藏色散人Original
2019-06-01 15:06:3710225browse

How to write java constructor method

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!

Statement:
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