接口类型的变量 [英] variable of Interface type
问题描述
我正在学习Java,我在书中看到了关于界面的以下描述:
I am learning Java, I saw the following description regards to interface in a book:
一个变量被声明为接口类型,它只是
意味着该对象应该已经实现了该接口。
When a variable is declared to be of an interface type, it simply means that the object is expected to have implemented that interface.
这是什么意思?如果我定义界面:
public interface Myinterface{
void method_one();
int method_two();
}
然后,我声明变量是一个接口类型,例如:
Then, I declare a variable to be of an interface type for example:
Myinterface foo = new Myinterface();
- 接口如何实现?
- 在什么情况下我应该定义一个接口类型变量?
我完全对这本书的描述感到困惑......
I completely get confused by the book's description...
推荐答案
你无法实例化一个接口,即你无法做到
You cannot instantiate an interface, i.e. you cannot do
MyInterface foo = new MyInterface(); // Compile-time error.
您可以做的是实例化实现接口的类。也就是说,给定一个类 MyClass
What you can do is instantiate a class that implements the interface. That is, given a class MyClass
public class MyClass implements MyInterface {
// ...
@Override
void method_one() {
// ...
}
@Override
int method_two() {
// ...
}
}
你可以实例化它并在你的变量中添加一个引用,如下所示:
you can instantiate it and place a reference to it in your variable like this:
MyInterface foo = new MyClass();
如果你有另一个类实现 MyInterface
If you had another class implementing MyInterface
class MyClass2 implements MyInterface {
// ...
}
你也可以用你的变量替换对这个类的实例的引用:
you can also substitute a reference to this class's instance under your variable:
MyInterface foo = new MyClass2();
这是接口的力量所在:它们定义类型,而不是一个特定的实现,让你引用给定类型的任何实现。
This is where the power of interfaces lies: they define types, not a particular implementation and let you refer to any implementation of a given type.
使类实现接口是一个非常好的编程习惯使用这些来引用这些类的实例。这种做法有助于提供大量的灵活性和重用。
It is a very good programming practice to make classes implement interfaces and to use these to refer to instances of these classes. This practice facilitates a great deal of flexibility and reuse.
因此,只要可以想到可以将不同的实现传递给方法,就应该使用接口类型参数和变量正在实施。例如,如果您使用的是 HashSet< T>
实例,则应使用类型的变量Set< T>
引用它(类 HashSet< T>
实现接口设置< T>
)。
Therefore, you should use interface type arguments and variables whenever it is conceivable that different implementations may be passed into the method you're implementing. For example, if you're working with a HashSet<T>
instance, you should use a variable of type Set<T>
to refer to it (class HashSet<T>
implements interface Set<T>
).
这篇关于接口类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!