(八)有关super的注意事项

我们可以在一个子类中使用super来调用父类中的方法,例如父类中的构造方法,不过在使用super时,我发现了一些问题:

复制代码
public class test {
    test(){
        call();
    }
    public void call(){
        System.out.println("father");
    }
    public static void main(String args[]){
        test t = new t();
    }
}
class t extends test{
    t(){
        super();
        call();
    }
    public void call(){
        System.out.println("child");
    }
}
复制代码

上述代码中,子类重构了父类中的call()方法,子类在构造函数中调用了父类的构造函数与call()方法,父类的构造函数也调用了call()方法,

我预期的结果是:  

father

child

运行结果是:

      

也就是说,super()即父类构造函数中调用的call()方法同样是子类重构后的方法

为了验证我心中的想法,我写了如下代码:

复制代码
public class test {
    public void call(){
        System.out.println("father");
    }
    public void Call(){
        call();
    }
    public static void main(String args[]){
        test t = new t();
    }
}
class t extends test{
    t(){
        super.Call();
    }
    @Override
    public void call(){
        System.out.println("child");
    }
    @Override
    public void Call(){
        call();
    }
}
复制代码

输出结果为:

    

为了更进一步的观察,我在父类的调用上面加了this关键字

复制代码
public class test {
    public void call(){
        System.out.println("father");
    }
    public void Call(){
        this.call();
    }
    public static void main(String args[]){
        test t = new t();
    }
}
class t extends test{
    t(){
        super.Call();
    }
    @Override
    public void call(){
        System.out.println("child");
    }
    @Override
    public void Call(){
        call();
    }
}
复制代码

得到了同样的结果

也就是说,只要不是用super所直接调用的方法,都将调用子类中重构的方法。比如:super.first()将会调用父类中的first()方法,但是若父类的first()方法实现过程中调用了second方法,且second方法被子类重构,则父类的first()方法会调用子类重构的second()方法而不是父类的second()方法

因此,当我们使用super调用父类方法时一定要注意该问题,如果super调用方法实现有对父类另一个方法的调用时,一定要慎重

猜你喜欢

转载自www.cnblogs.com/szjk/p/11075141.html
今日推荐