gpt4 book ai didi

java - 接口(interface)只是编译时依赖吗?

转载 作者:太空宇宙 更新时间:2023-11-04 12:41:25 24 4
gpt4 key购买 nike

假设我有一个如下所示的界面;

public interface aitf{
public void method1();
}

和一个实现类;

public class a implements aitf{
public void method1(){
System.out.println("method 1");
}
public static void main(String... args){
new a().method1();
}
}

它会按预期运行并打印如下。

method 1

然后,如果我更改并添加一个方法并重新编译接口(interface);

public interface aitf{
public void method1();
public void method2();
}

具体类(a)仍在工作。实际上这种行为是有道理的,因为否则所有 api 更改都会导致问题。但是如何解释这种行为,接口(interface)只是编译时依赖吗?

最佳答案

让我们回到接口(interface)的根源,即多态性

  • 多态性之前:

    • 控制流由系统行为决定,源代码依赖性由控制流决定。
  • 多态性发挥作用后:

    • 我们通过使用接口(interface)应用了依赖倒置,这使我们能够在任何组件中的源代码发生更改时实现独立的可部署性,而这一切都发生在编译时

Compile-time errors are generally referred to the error corresponding to syntax or semantics. Runtime errors on the other hand refer to the error encountered during the execution of code at runtime. Compile-time errors get detected by compiler at the time of code development

Interfaces运行时中并不存在,但它只存在于编译时中,因为它是在OOP中应用依赖倒置的直接结果

在您的情况下,您的接口(interface)旧编译是一致的,因此当您重新编译新接口(interface)时,它不会反射(reflect)在上,直到该类也再次重新编译以维持接口(interface)契约中的更改。

引自Docs :

Method and Constructor Overloading:Adding new methods or constructors that overload existing methods or constructors does not break compatibility with pre-existing binaries. The signature to be used for each invocation was determined when these existing binaries were compiled; therefore newly added methods or constructors will not be used, even if their signatures are both applicable and more specific than the signature originally chosen.While adding a new overloaded method or constructor may cause a compile-time error the next time a class or interface is compiled because there is no method or constructor that is most specific (§15.12.2.5), no such error occurs when a program is executed, because no overload resolution is done at execution time.

关于java - 接口(interface)只是编译时依赖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798634/

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