我正在学习Java,我在一本书中看到了关于接口(interface)的描述:
When a variable is declared to be of an interface type, it simply means that the object is expected to have implemented that interface.
这是什么意思?如果我定义一个接口(interface):
public interface Myinterface{
void method_one();
int method_two();
}
然后,我将一个变量声明为接口(interface)类型,例如:
Myinterface foo = new Myinterface();
- 接口(interface)是如何实现的?
- 什么情况下应该定义接口(interface)类型变量?
我完全被这本书的描述弄糊涂了......
最佳答案
你不能实例化一个接口(interface),也就是说你不能这样做
MyInterface foo = new MyInterface(); // Compile-time error.
您可以做的是实例化一个实现该接口(interface)的类。也就是说,给定一个类 MyClass
public class MyClass implements MyInterface {
// ...
@Override
void method_one() {
// ...
}
@Override
int method_two() {
// ...
}
}
您可以像这样实例化它并在您的变量中放置对它的引用:
MyInterface foo = new MyClass();
如果你有另一个实现 MyInterface
的类
class MyClass2 implements MyInterface {
// ...
}
您还可以在您的变量下替换对此类实例的引用:
MyInterface foo = new MyClass2();
这就是接口(interface)的强大之处:它们定义类型,而不是特定的实现,并让您引用给定类型的任何实现。
让类实现接口(interface)并使用这些接口(interface)来引用这些类的实例是一个很好的编程习惯。这种做法极大地促进了灵 active 和重用。
因此,只要可以想到不同的实现可能会传递到您正在实现的方法中,您就应该使用接口(interface)类型参数和变量。例如,如果您正在使用 HashSet<T>
例如,您应该使用 Set<T>
类型的变量引用它(类 HashSet<T>
实现接口(interface) Set<T>
)。
关于java - 接口(interface)类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406250/