温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java子类调用父类的方法中包含子类重写的实例方法

发布时间:2020-09-04 16:04:58 来源:脚本之家 阅读:171 作者:斜月三星一太阳 栏目:编程语言

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

# 先看代码:

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()方法;

以上就是本次介绍的全部知识点内容,感谢大家的阅读和对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI