this构造
public class Apple{
public String name;
public String color;
public double weight;
// 无参构造
public Apple()
{
}
// 两个参数的构造
public Apple(String name, String color)
{
this.name = name;
this.color = color;
}
// 三个参数的构造
public Apple(String name, String color, double weight)
{
// 通过this 调用另一个重载的构造器的初始化代码
this(name, color);
this.weight = weight;
}
}
super构造
public class Base {
public double size;
public String name;
public Base(double size, String name)
{
this.size = size;
this.name = name;
}
}
public class Sub extends Base{
public String color;
public Sub(double size, String name, String color) {
// 通过 super 调用父类构造器
super(size, name);
this.color = color;
}
}
public class Test {
public static void main(String[] args) {
Sub s = new Sub(5.6, "测试对象", "红色");
System.out.println(s.size + "--" + s.name + "--" + s.color);
}
}
总结:
this
调用的是同一个类中的重载的构造器
super
调用的是其父类的构造器
注意点
super调用父类构造器必须出现在子类构造器的第一行