使用 Class 名称调用接口 class 对象与接口名称之间的区别
Difference Between Calling an interfaced class object with the Class name vs the Interface name
请看下面的例子
public interface Testing {
public void go();
}
public class TestingImplements implements Testing {
@Override
public void go() {
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Testing throughInterface = new TestingImplements();
TestingImplements directly = new TestingImplements();
}
}
我的问题是,
直接使用 throughInterface 有什么优点和缺点。一点解释会很有帮助。
Testing throughInterface = new TestingImplements();
而不是
TestingImplements directly = new TestingImplements();
接口的目的是实现多重继承,但在您的情况下,如果您想更改另一个 class 中方法的行为,那么这将很有用。
让我们来定义这两种不同方法的含义:
当你说 Testing throughInterface = new TestingImplements();
时,你正在为接口编程。
当您说 TestingImplements directly = new TestingImplements();
时,您正在为实现编程。
使用 1) 相对于 2) 的优势
- 编译时间优势:您可以在不更改引用的情况下更改要实例化的对象的类型,并且请放心代码将编译。例如,您可以说
Testing throughInterface = new TestingImplementsTwo();
并且不需要更改其余代码,因为您知道 TestingImplementsTwo
将至少包含 Testing
中存在的那些方法
- 运行时间优势:您可以通过控制反转在运行时间交换实现。
请看下面的例子
public interface Testing {
public void go();
}
public class TestingImplements implements Testing {
@Override
public void go() {
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Testing throughInterface = new TestingImplements();
TestingImplements directly = new TestingImplements();
}
}
我的问题是, 直接使用 throughInterface 有什么优点和缺点。一点解释会很有帮助。
Testing throughInterface = new TestingImplements();
而不是
TestingImplements directly = new TestingImplements();
接口的目的是实现多重继承,但在您的情况下,如果您想更改另一个 class 中方法的行为,那么这将很有用。
让我们来定义这两种不同方法的含义:
当你说
Testing throughInterface = new TestingImplements();
时,你正在为接口编程。当您说
TestingImplements directly = new TestingImplements();
时,您正在为实现编程。
使用 1) 相对于 2) 的优势
- 编译时间优势:您可以在不更改引用的情况下更改要实例化的对象的类型,并且请放心代码将编译。例如,您可以说
Testing throughInterface = new TestingImplementsTwo();
并且不需要更改其余代码,因为您知道TestingImplementsTwo
将至少包含Testing
中存在的那些方法 - 运行时间优势:您可以通过控制反转在运行时间交换实现。