For example, I often see something like this:
例如,我经常看到这样的事情:
Queue<String> q = new LinkedList<String>();
I totally understand the point that by declaring it as a type of Queue, any class that implements Queue interface can be used to instantiate the object.
我完全理解这一点,通过将其声明为Queue类型,任何实现Queue接口的类都可用于实例化对象。
What bothers me is that often I see something like
困扰我的是,我常常看到类似的东西
q.size()
to get the size of the Queue.
获取队列的大小。
This compiles and works fine, but to me, doing something like this defeats the concept of "interface", because size() is a method in LinkedList class.
这编译并且工作正常,但对我来说,做这样的事情会破坏“接口”的概念,因为size()是LinkedList类中的一个方法。
Essentially we need to be aware of what class was used to instantiate the queue object. If we later decided to use a different class to instantiate this queue object, then we may run into trouble
基本上我们需要知道用于实例化队列对象的类。如果我们后来决定使用另一个类来实例化这个队列对象,那么我们可能会遇到麻烦
e.g. if we decide NOT to use LinkedList class and decide to use to some other class to instantiate the queue object, we need to make sure that the new class also has the method size(), otherwise we will need to change it.
例如如果我们决定不使用LinkedList类并决定使用其他类来实例化队列对象,我们需要确保新类也有方法size(),否则我们需要更改它。
Note: I am using size() method just as an example. Potentially, any method that LinkedList has can be called on the queue object right? What would we do if we later decided to use some other class to instantiate the queue object? We need to make sure that this new class also has the same method, right? This seems to be defeating the purpose of interface. If we declare a variable as an interface type, we should only be using the methods specific to that interface.
注意:我正在使用size()方法作为示例。潜在地,可以在队列对象上调用LinkedList具有的任何方法吗?如果我们后来决定使用其他类来实例化队列对象,我们会怎么做?我们需要确保这个新类也有相同的方法,对吧?这似乎是打败了界面的目的。如果我们将变量声明为接口类型,我们应该只使用特定于该接口的方法。
Am I missing some points here?
我在这里错过了一些观点吗?
1 个解决方案
#1
3
Any Queue
implementation would have the size()
method, since size()
is a method of the Collection
interface, which the Queue
interface extends. Therefore, size()
belongs to the Queue
interface indirectly.
任何Queue实现都具有size()方法,因为size()是Queue接口扩展的Collection接口的方法。因此,size()间接属于Queue接口。
#1
3
Any Queue
implementation would have the size()
method, since size()
is a method of the Collection
interface, which the Queue
interface extends. Therefore, size()
belongs to the Queue
interface indirectly.
任何Queue实现都具有size()方法,因为size()是Queue接口扩展的Collection接口的方法。因此,size()间接属于Queue接口。