简体   繁体   中英

Why do we allow interface to be used as a type in Java?

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.

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.

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

eg 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.

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.

Am I missing some points here?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM