构造器的特征
- 它具有与类相同的名称
- 它不声明返回值类型(与声明为void不同)
- 不能被static、final、synchronized、abstract、native修饰,不能有return语句返回值
构造器的作用
- 创建对象并给对象进行初始化
例如:
public class Demo {
public static void main(String[] args) {
// 创建类的对象: new + 构造器
Person people = new Person();
people.eat();
}
}
class Person{
// 属性
String name;
int age;
// 构造器 1
public Person(){
System.out.println("定义构造器");
}
// 构造器 2
// 初始化对象
public Person(String name){
this.name = name;
}
// 方法
public void eat(){
System.out.println("eating");
}
}
<br />