gpt4 book ai didi

java - 调用Java接口(interface)方法的困惑

转载 作者:IT老高 更新时间:2023-10-28 20:37:33 25 4
gpt4 key购买 nike

假设我有一个接口(interface)A,定义如下:

public interface A {
public void a();
}

它包括名为void a();

的方法

我有一个类实现了这个接口(interface)并且只有一个方法:

    public class AImpl implements A {
@Override
public void a() {
System.out.println("Do something");
}
}

问:如果在主类中调用接口(interface)方法,会不会调用属于实现该接口(interface)的类的实现?

例如:

public static void main(String[] args){
A aa;
aa.a();
}

这会打印“做某事”吗?

最佳答案

A aa = new AImpl();
aa.a();

这里你的引用变量是接口(interface) A 类型但实际的 ObjectAImpl

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.

阅读更多关于 Documentation

接口(interface)引用在实现 A 接口(interface)时可以保存 AImpl 的对象。

关于java - 调用Java接口(interface)方法的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16174260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com