构造方法中Super的作用
作用:继承并执行父类的无参构造方法;如果将原来的super()==>super(参数),则继承并执行父类的有参构造方法。需要注意的是在类的继承中,super()在子类的构造方法中是默认存在的。
PS:如果你有一天忘记了这个知识点,此文又且恰好很幸运地被你点开请复制一下代码,并运行一下,然后就会豁然开朗。如果问题解决了,希望能给个免费的赞哦!!!
public class As {
public static void main(String[] args) {
Cat c = new Cat(); //---------------(1)
System.out.println("-------------------");
Cat c1 = new Cat("花花",4); //----------------(2)
}
}
class Animal {
private String color;
private int foot;
public Animal(){
System.out.println("父类无参数构造器=======1");
}
public Animal(String color,int foot){
System.out.println("父类有参数构造器=======3");
this.color = color;
this.foot = foot;
}
}
class Cat extends Animal{
public Cat(){
super(); //---------------可以省略
System.out.println("子类无参数构造器========2");
}
public Cat(String color,int foot){
//super(); //---------------可以省略
super(color,foot); //---------------(3)
//super("草草",4);
System.out.println("子类有参数构造器======4");
}
}