[英]Which method is getting executed when they have the same implementation of the same interface?
There is an interface with a method called有一个接口,有一个方法叫做
foo(boolean arg1, String arg2);
Additionally I have two classes which implement this method.另外我有两个实现这个方法的类。 Now when I call the foo method from the interface, how does it decide which implementation to pick?
现在当我从接口调用 foo 方法时,它如何决定选择哪个实现?
The 2 implementations take the same parameters and return the same object but differ in the implementation.这两种实现采用相同的参数并返回相同的对象,但实现方式不同。
When you call你打电话时
a.foo(b, c);
it looks at the type of the object a
points to, not the type of the reference and calls the method that type implements.它查看
a
指向的对象的类型,而不是引用的类型,并调用该类型实现的方法。
Initially, it uses a virtual lookup table, which as you can image is expensive, so in the Oracle/OpenJDK JVM, it can inline up to two virtual methods dynamically based on usage so it looks more like this.最初,它使用一个虚拟查找表,你可以想象它是昂贵的,所以在 Oracle/OpenJDK JVM 中,它可以根据使用情况动态内联最多两个虚拟方法,所以它看起来更像这样。
if (a instanceof Type1) {
((Type1) a).foo(b, c);
} else (a instanceof Type2) {
((Type2) a).foo(b, c);
} else {
a.foo(b, c); // do a full vtable lookup.
}
You cannot call methods on an interface... You need to call them on an object (an instance of a class implementing your interface).您不能在接口上调用方法...您需要在对象(实现您的接口的类的实例)上调用它们。 and that is the code that is called.
这就是被调用的代码。
I believe you asking about using interface methods in othere (default) interface methods.我相信您询问在其他(默认)接口方法中使用接口方法。
Method will be chosen based on instance referenced by interface variable.方法将根据接口变量引用的实例进行选择。 Here is small example
这是小例子
class Scratch {
public static void main(String[] args) {
ClassA varClassA = new ClassA();
ClassB varClassB = new ClassB();
Bar interfaceVar = varClassA;
interfaceVar.foo("firstCall");
interfaceVar = varClassB;
interfaceVar.foo("secondCall");
varClassA.foo("call from A");
varClassB.foo("call from B");
interfaceVar = new Bar() { // or just interfaceVar = System.out::println
@Override
public void printParam(String params) {
System.out.printf("Anonimus class: %s%n", params);
}
};
interfaceVar.foo("Anonimus call");
}
public interface Bar {
default void foo(String param) {
printParam(param);
}
void printParam(String params);
}
public static class ClassA implements Bar {
@Override
public void printParam(String params) {
System.out.println(String.format(
"Called from %s wth params: %s",
this.getClass().getName(),
params)
);
}
}
public static class ClassB implements Bar {
@Override
public void printParam(String params) {
System.out.printf("param from ClassB:%s%n", params);
}
}
}
Output:输出:
Called from Scratch$ClassA wth params: firstCall
param from ClassB:secondCall
Called from Scratch$ClassA wth params: call from A
param from ClassB:call from B
Anonimus class: Anonimus call
Process finished with exit code 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.