如何解决抽象类的一个方法调用同一个抽象类的另一个方法在这种情况下到底发生了什么?
abstract class Animal {
public void test1() {
System.out.println(" Animal test1");
test2();
}
public void test2() {
System.out.println(" Animal test2");
}
}
class Cat extends Animal {
@Override
public void test2() {
System.out.println(" Cat Test2 ");
}
}
public class MyClass {
public static void main(String [] args) {
Animal a = new Cat();
a.test1();
}
}
所以,
为什么第一个调用是 Animal 类的 test1 方法? 以及,为什么从 test1() 方法调用 test2() 方法解析为子类的 test2() 方法?
我试图从 Call method from another method in abstract class with same name in real class 中理解,但不能理解很多。
解决方法
发生这种情况是因为 Method Overriding 的概念。
声明
Animal a = new Cat();
将 Cat 类型的对象分配给 Animal 类型的引用。 当声明
a.test1();
被执行。运行时环境推断 a 的类型,即 Cat。由于Cat 类没有定义自己的test1() 方法,它调用从Animal 类继承的方法。
同样,当遇到对 test2() 的调用时,首先检查 Cat 类方法。因为,Cat 类有一个 test2() 方法,其签名与 Animaltest2() 方法完全相同。 /strong> 类,Cat 类方法被调用。这个概念被称为方法覆盖。
简而言之,当我们尝试使用超类引用调用子类方法时,它首先检查该方法,在子类中,然后是它的超类,依此类推。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。