构造器

63 阅读1分钟

创建对象时,会创建构造器

package com.itheima.constructor;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("张三", 99);
        System.out.println(s1.name);
        System.out.println(s1.score);
    }
}

package com.itheima.constructor;

public class Student {
    String name;
    double score;

    public Student() {
        System.out.println("无参数构造器执行了");
    }

    public Student(String name, double score) {
        System.out.println("有参数构造器执行了");
        this.name = name;
        this.score = score;
    }
}
  • this指向当前的对象
  • 当没有写constructor构造器时,创建实例时会自动创建无参数的构造器
  • 创建实例没有传参数,执行无参数构造器,否则执行有参数构造器