在继承中,子类默认会有super()的存在,它的作用是调用父类的构造方法。
如下:
package cn.itcast.domain;
public class Test {
public static void main(String[] args) {
Cat cat = new Cat();
System.out.println("=========");
Cat cat2 = new Cat("hua","black");
}
}
class Animal {
public String name;
public String color;
public Animal() {
System.out.println("父类无参构造");
}
public Animal(String name, String color) {
System.out.println("父类有参构造");
}
}
class Cat extends Animal {
public Cat() {
super();//可以省略
System.out.println("子类无参构造");
}
public Cat(String name, String color) {
super();//可以省略
System.out.println("子类有参构造");
}
}
输出:
子类实例化时会先调用父类的构造方法。
class Cat extends Animal {
public Cat() {
super();
System.out.println("子类无参构造");
}
public Cat(String name, String color) {
super(name, color);
System.out.println("子类有参构造");
}
}
当super()中带参时,会调用父类的有参构造,上面输出如下:
综上:super() 会调用父类的无参构造方法,可以省略;super(name, color)会调用父类的有参构造。