构造器的特征
- 它具有与类相同的名称
- 它不声明返回值类型(与声明为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;// 构造器 1public Person(){System.out.println("定义构造器");}// 构造器 2// 初始化对象public Person(String name){this.name = name;}// 方法public void eat(){System.out.println("eating");}}
<br />
