假设我有一个如下所示的界面;
public interface aitf{
public void method1();
}
Run Code Online (Sandbox Code Playgroud)
和一个实现类;
public class a implements aitf{
public void method1(){
System.out.println("method 1");
}
public static void main(String... args){
new a().method1();
}
}
Run Code Online (Sandbox Code Playgroud)
它按预期运行并打印如下。
method 1
Run Code Online (Sandbox Code Playgroud)
然后,如果我更改并添加一个方法并重新编译接口;
public interface aitf{
public void method1();
public void method2();
}
Run Code Online (Sandbox Code Playgroud)
具体类(a)仍在工作。实际上这种行为是有道理的,因为否则所有 api 更改都会导致问题。但是如何解释这种行为,接口只是编译时依赖吗?
让我们回到 的根源Interfaces,即polymorphism。
前polymorphism:
polymorphism投入使用后:
Dependency inversion通过 using进行应用Interfaces,这使我们实现了独立的可部署性,当任何组件中的源代码发生更改时,这一切都发生在compile time.\n\n编译时错误一般指语法或
\nsemantics. 另一方面,运行时错误是指在运行时执行代码期间遇到的错误。编译时错误在代码开发时被编译器检测到
Interfaces不存在于Runtime,但它仅存在于,因为它是应用incompile time的直接结果Dependency inversionOOP
在你的情况下发生的情况是,你的与你的class是内聚的,所以当你重新编译你的时,它不会反映到 ,直到类也再次保持 的变化。old compilationinterfacenew interfaceclassrecompiledcontractinterface
引用文档:
\n\n\n\n
Method and Constructor Overloading:\n添加重载现有方法或构造函数的新方法或构造函数不会破坏与预先存在的二进制文件的兼容性。每次调用使用的签名是在编译这些现有二进制文件时确定的;因此,即使新添加的方法或构造函数的签名均适用且比最初选择的签名更具体,也不会使用它们。\n添加新的重载方法或构造函数可能会在下次类或接口时导致编译时错误被编译是因为没有最具体的方法或构造函数(\xc2\xa715.12.2.5),执行程序时不会发生此类错误,因为在执行时没有进行重载解析。
| 归档时间: |
|
| 查看次数: |
1378 次 |
| 最近记录: |