用Java如何实现继承? [英] How is inheritance implemented in Java?

查看:100
本文介绍了用Java如何实现继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中实现继承?例如,考虑一下:

How exactly is inheritance implemented in Java? For example, consider this:

class A {
    public void foo() {
         System.out.print("A");
    }
}
class B extends A {
    ...
}
class Test {
    public static void main(String[] args) {
        B test = new B();
        test.foo(); // how is foo() called?
}

下面,编译器是否将A.foo()的定义转储到B类的主体中?像

Below the line, would the compiler just dump the definition of A.foo() into the body of class B? Like

class B extends A {
    ...
    public void foo() {
         System.out.print("A");
    }
}

或者foo是否以某种方式在A类中查找并在那里被调用?

Or is foo somehow looked up in class A and called there?

推荐答案

方法主体不会复制到子类的未定义方法主体中.相反,当您致电

Method bodies aren't copied in the undefined method body of a subclass. Instead, when you call

B test = new B();
test.foo();

它将看起来像其层次结构,每次找不到实现时都会上一层. 首先,它将检查没有实现的B.在A之上的一级上,它会使用它.

It will look trough its hierarchy, going up a level every time it can't find an implementation. First it will check B which has no implementation. One level above that there's A which does, so it will use that one.

这篇关于用Java如何实现继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆