子函数调用父函数,父函数调用的方法,子函数重写了,那么最后父函数调用的是自己的方法,还是子函数的方法。

本文探讨了子类重写父类方法时的行为,特别是在父类方法内部调用了被子类重写的方法的情况。通过实例代码展示了如何实现方法的正确调用,并介绍了使用super关键字来调用父类方法的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q:子类调用父类的方法,父类中某个方法所调用的方法,子类也重写了,那么最后父类中的方法调用的是自己的方法,还是子类的方法。

A:调用的是子类的方法。

    看代码:

public class Parent {
    public void usedMethod(){
        say();
    }
    public void say(){
        System.out.println("this is the parent!");
    }
}
public class Child extends Parent {
    public static void main(String[]args){
        Child child=new Child();
        child.usedMethod();
    }
    public void say(){
       /*super.say();*/
        System.out.println("this is child");
    }
}

result:

    this is child!

    Process finished with exit code 0

    个人理解:

    继承其实将父类的成员变量和成员方法拷贝到自身的内存空间,对于重写的方法,就不用拷贝了。

Q:如果子类想让父类调用父类的方法,而不是子类的方法,怎么办呢?

A:在子类的方法中显示调用super.***。

看代码:

    

public class Child extends Parent {
    public static void main(String[]args){
        Child child=new Child();
        child.usedMethod();
    }
    public void say(){
        super.say();
       /* System.out.println("this is child");*/
    }
}


result:

    

this is the parent!

Process finished with exit code 0
父函数已经写好了,当要重写父函数的方法时,要注意父函数别的方法有可能会调用,尽量别重写,可以采用重载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值