软件编程
位置:首页>> 软件编程>> java编程>> java子类调用父类的方法中包含子类重写的实例方法

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

作者:斜月三星一太阳  发布时间:2023-12-22 21:14:50 

标签:java,子类,父类

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

# 先看代码:


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

来源:https://www.cnblogs.com/lwmp/p/11518023.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com