【39】父类子类中关于super

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/azhegps/article/details/53585340
public class Test {
    public static void main(String[] args) {
        System.out.println(new BigDog("大黑狗", "黑色"));
    }
}

class Dog {
    String name;
//    public Dog() {
//        super();
//    }

    public Dog(String name) {
        super();
        this.name = name;
    }

    public String toString() {
        return "name:" + name;
    }
}

class BigDog extends Dog {
    String color;

    public BigDog(String name, String color) {
//        super(name);
        this.name = name;
        this.color = color;
    }

    public String toString() {
        return "name:" + name + ", color:" + color;
    }
}

/**
 *
 主程序编译不通过。
 如果一个类没有写无参数构造函数时,系统会默认给该类添加一个没有参数的构造函数;
 如果一个类写了构造函数,那么系统就不会给该类在添加默认的构造函数。

 当一个子类调用自己的构造函数时,会先去调用父类的构造函数;如果没有用super(参数…)进行明显的调用父类的构造函数,
 那么它会默认调用super()父类默认的构造函数,这里父类中没有写默认无参的构造函数,所以当父类中添加了带参数的构造函数时,
 最好要写一个不带参数的构造函数,以便有子类继承时调用。
 */

猜你喜欢

转载自blog.csdn.net/azhegps/article/details/53585340