天天看点

super与构造方法

我先把题目贴出来,一点都不懂的就看我对照这几个题讲解super再联系后面的习题

class Super {
    public Super() {
        System.out.println("Super()");
    }

    public Super(String str) {
        System.out.println("Super(String)");
    }
}

public class Sub extends Super {

    public Sub() {
        super();
        System.out.println("Sub()");
    }

    public Sub(int i) {
        this();
        System.out.println("Sub(int)");
    }

    public Sub(String str) {
        super(str);
        System.out.println("Sub(String)");
    }

    public static void main(String[] args) {
        Sub s1 = new Sub();
        Sub s2 = new Sub(10);
        Sub s3 = new Sub("hello");
    }
}
           

不要说我不写测试类哇,我这个是为了方便

super与构造方法

首先子类继承父类

子类继承父类的话会先实现父类的构造方法!!!及时不写super();都会优先实现父类的无参构造

Sub s1 = new Sub();当读到这一条时应该先实现Super的无参构造

System.out.println(“Super()”);

再实现Sub的无参构造

System.out.println(“Sub()”);

Sub s2 = new Sub(10);中有一个int类型的参数

那我们回过头去找找

public Sub(int i) {
        this();
        System.out.println("Sub(int)");
    }
           

大家可能有问题这个this()是个啥

super与构造方法

this() 大家看里面是没东西的,那么他指的是子类的还是父类的呢?

他这里的this()应该指的是就近的无参构造就是Sub()

!!!那么调用了Sub()那就要实现Sub()的父类无参构造不然没有爸爸哪来的儿子

就把无参构造又走了一遍答案就是

System.out.println(“Super()”);

System.out.println(“Sub()”);

再看到 Sub s2 = new Sub(10);他父类没有int 参数的方法那就直接执行呗

System.out.println(“Sub(int)”);

最后:

**Sub s3 = new Sub(“hello”);**子类和父类中都有String类型的就有是先执行父类构造方法再执行子类构造方法咯

System.out.println(“Super(String)”);

System.out.println(“Sub(String)”);

所以最后答案显而易见咯

//Super()

//Sub()

//Super()

//Sub()

//Sub(int)

//Super(String)

//Sub(String)