加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java继承-子类调用父类的方法中包含子类重写的方法

发布时间:2020-12-15 07:46:06 所属栏目:Java 来源:网络整理
导读:# 看题目是不是很绕,这个我也不知道怎么才能更简单的表达了。。。 # 先看代码: public class Common { public static void main(String[] args) { Sub sub = new Sub(); sub.testSub(); }} class Parent { protected boolean test() { throw new RuntimeEx

# 看题目是不是很绕,这个我也不知道怎么才能更简单的表达了。。。

# 先看代码:

public class Common {

    public static void main(String[] args) {
        Sub sub = new Sub();
        sub.testSub();
    }
}

class Parent {

    protected boolean test() {
        throw new RuntimeException();
    }

    protected void testParent() {
        if (test()) {
            System.out.println(this.getClass().getName());
        }
    }

}

class Sub extends Parent {

    public void testSub() {
        super.testParent();
    }

    @Override
    public boolean test() {
        return true;
    }
}

# 上面的代码的输出结果是:
com.qq.demo.common.Sub

# 大致流程是 main 中调用子类的 testSub()方法 -- testSub()方法中调用父类的testParent() 方法 -- testParent() 方法调用test()方法;需要注意的是test()方法在父类和子类中都存在,子类重写了父类的test()方法;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读