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

How to write java constructor method

藏色散人
Release: 2019-06-01 15:06:37
Original
10262 people have browsed it

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

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!

Related labels:
source:php.cn
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