vmayer
vmayer

Reputation: 1063

Using interfaces over classes

I'm a bit confused about the advice to use the Interface for a Java class, like in this thread: Why should the interface for a Java class be preferred?

I understand why you would want to use the interface: if something changes later you have less code to clean up.

But aren't there cases in which using the Interface would prevent you from being able to take advantage of the performance reason why you chose that particular class in the first place?

For instance, if I have a TreeMap, I assume that I should be able to locate any element in at most O(logn). That's why it has nice methods I can take advantage of like higherEntry(), lowerEntry(), lastEntry().

If I instead reference this TreeMap as a Map, now I believe I am forced to iterate one element at a time through my list in O(n) to locate that entry.

I'm new to Java, so let me know if I'm missing something here.

Upvotes: 2

Views: 104

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198123

If you want to use methods like higherEntry, lowerEntry, and lastEntry, then just use the NavigableMap interface instead of the Map interface or the TreeMap class.

In general, use interfaces as often as possible, and use the most general interface you can that supports all the operations you'd want to use.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213261

If I instead reference this TreeMap as a Map, now I believe I am forced to iterate one element at a time through my list in O(n) to locate that entry.

No you are not forced to do that. If you are sure that your Map reference is holding a reference to TreeMap, and you want to access specific method of TreeMap, then you can always typecast the Map reference to a TreeMap reference, and then access the appropriate method, like, higherEntry(), lowerEntry(). But, the only caveat is that, you have to be sure that your Map reference is actually pointing to a TreeMap, to avoid getting a ClassCastException at runtime.

This is implied by the fact that, a super class and it's sub classes are covariant in nature. So, you can perform cast between them, provided you are not breaking the rules at runtime (That is having the super class reference holding the reference to some other sub class instance, which is not covariant with the sub class you are casting to).

Now for your example, since the TreeMap also implements the NavigableMap interface, which is a sub interface of Map interface, so you can use it instead of Map interface. So, you can have the advantage of polymorphism, without the need to typecast.

Upvotes: 2

Related Questions