5

継承 (複数、仮想など) が存在する場合に C++ が仮想テーブルを管理する方法と、オブジェクトをメモリに配置する方法について多くのことを学びました。

現在、Java は単一行の継承のみを考慮する必要があり、インスタンス メソッドの非表示などは必要ないため、この場合、仮想テーブルは少し単純になるはずです。私は、Classファイルがメソッド領域への「ゲートウェイ」として機能することを知っています。ここには、メソッドのバイトコードを含む型定義が格納されていると思います。次の 2 つの質問が頭に浮かびます。

  1. 一般にJavaにはvtable/methodテーブル構造がありますか? どのように保存され、Classオブジェクトにリンクされますか?
  2. 継承/動的メソッド呼び出しはどのように解決されますか? つまり、次のとおりです。

次のクラスとインスタンス化があります。

class A{ int f(){...} }
class B extends A{ int f(){...} }

A a = new B();
a.f();

B の f() が呼び出されます。B のファイルを解決する AClassは正しいメソッド ポインターですか?

コメントをお寄せいただきありがとうございます。

4

3 に答える 3

4

In Java only what it must do is specified, how it does it is not. This has some advantages in that the code can be optimised in ways C++ doesn't allow. For example, "virtual" methods can be inlined by the JVM even if they are from a different library/jar.

于 2012-04-19T10:03:24.973 に答える
4

への呼び出しa.f()は、Java バイトコード アセンブリ言語で次のように実現されます。

aload_1 // load the local variable a, here from local address 1
invokevirtual with index into the constant pool for
    method ref:
        class "A"
        nameAndType "f", "()I"

おそらく実行時に、vtable は Bf() の呼び出しを解決します。しかし、ご覧のとおり、クラスの形式は非常に抽象的であり、JVM は「効率的な」実装のためにクラスを自由にロードできます。

于 2012-04-19T10:26:37.973 に答える
3

Here is a related question with answers containing proper links. One thing to note, that was not articulated in the SO question I reference, is that all methods in Java are implicitly virtual. If curious about the technical details, have a look at the jvm.h (search for the string "vtable").

于 2012-04-19T10:02:10.637 に答える