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调用方法实现有对父类另一个方法的调用时,一定要慎重

转载于:https://www.cnblogs.com/code-thisworld/p/8933254.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值