混淆调用Java接口方法 [英] Confusion on call Java Interface method
问题描述
假设我有一个接口A,定义如下:
Let's say I have an Interface A, define as below:
public interface A {
public a();
}
它包含一个名为a的方法。
It include a method called a.
我有一个类实现这个接口,让我们说:
I have a class implement this interface, let's say:
public class AImpl implements A{
public void a()
{
println("Do something");
}
}
此类仅实现此方法。
这是我的问题:所以如果在主类中,我调用接口方法,它会调用实现接口的类中的方法吗?例如:
Here is my question: So if in the main class, i call interface method, will it call the method in the class which implement the interface? For example:
public static void main(String[] args){
A aa;
aa.a();
}
它会调用类AImpl中的方法并输出Do something吗?
Will it call the method in the class AImpl and output "Do something"?
推荐答案
A aa = new AImpl();
aa.a();
这里你的参考变量是接口 A
type但实际的对象
是 AImpl
。
Here your reference variable is interface A
type But actual Object
is AImpl
.
定义新接口时,您将定义新的参考数据
类型。您可以在任何可以使用任何其他数据
类型名称的地方使用接口名称。如果定义类型为
接口的引用变量,则为其分配的任何对象必须是实现接口的类
的实例。
When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
详细了解文档
接口引用可以在实现A接口时保存AImpl的Object。
A Interface reference can hold Object of AImpl as it implements the A interface.
这篇关于混淆调用Java接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!