Java 多态 JVM 层面实现 只是解析了类,本篇探析 interface 层面的实现。
测试代码
interface Eat
package com.example.demo.invokeinterface;
public interface Eat {
void eat();
}
interface Fly
package com.example.demo.invokeinterface;
public interface Fly {
void fly();
}
implementation Airplane
package com.example.demo.invokeinterface;
public class Airplane implements Fly {
@Override
public void fly() {
System.out.println("The airplane is flying!");
}
}
implementation Bat
package com.example.demo.invokeinterface;
public class Bat implements Eat, Fly {
@Override
public void eat() {
System.out.println("The bat is eating a frog! ");
}
@Override
public void fly() {
System.out.println("The bat is flying!");
}
}
Driver class
package com.example.demo.invokeinterface;
import java.util.concurrent.CountDownLatch;
public class InvokeInterfaceTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(10);
Airplane airplane = new Airplane();
Bat bat = new Bat();
airplane.fly();
bat.fly();
bat.eat();
countDownLatch.await();
}
}
各个类的 vtable 和 itable

如上图分析的有 5 个 class。Object、Eat、Fly、Airplane、Bat。注意这 5 个类的 vtable ,每一个条目指向的方法地址都一样。Airplane 和 Bat 这两个实现类的 itable 不一样。airplane和 bat调用的 fly方法并不同。这就是方法的动态指派。Airplane 的 itable 中包括了 Fly 这个 interface class 和实现的 fly方法。Bat 的 itable 包括了 Fly 和 Eat 这两个 interface class 和实现的 fly方法和 eat 方法。
本文探讨了Java中多态的实现机制,特别是在接口层面。通过具体的代码示例,展示了如何通过实现多个接口来体现多态性,以及JVM如何在运行时动态地选择正确的实现方法。
1231

被折叠的 条评论
为什么被折叠?



