If I have a few subtypes, each inheriting an abstract superclass and this superclass implements an interface- when implementing dynamic binding/polymorphism is there any difference between declaring the objects as the superclass type, opposed to the interface type?
So A,B,C,D extend from S and S implements I.
I could do:
S a = new A();
S b = new B();
or
I a = new A();
I b = new B();
I tend to use interfaces, but i’m suddenly wondering if its better to use the superclass in case you were to split the interface into two interfaces….
From a typing perspective, there is no difference. (Unless you specifically “go looking” by using reflection to introspect the types at runtime …)
From a runtime performance perspective, there is no difference. (Except from some possible very minor differences in the time to load classes … which can be ignored in all realistic use-cases.)
From an code implementation perspective, there are advantages and disadvantages in the two approaches:
If you use just superclasses (no interfaces), you may be able to write less code. But the flip-side is that your code is less flexible:
You are trying the external API to the implementation in a way that restricts your ability to write new implementations. The
java.io.OutputStreamclass is a classic example of this. Because it is a class, you have to create a subclass in order to implement a new stream type, and you may find that you have to code the subclass to override all infrastructure that you “inherit”.The fact a class can have just one superclass further restricts you to a tree-shaped API hierarchy.
Clients have to be coded against the implementation class APIs to a greater degree … because that is all there is. And that restricts the programmer’s ability to change his / her mind about.
Bottom line: If the particular use-case does not require you to be able to do these things (now or in the future) then using interfaces has no benefit. But few use-cases are really like that. And the incremental implementation effort of using interfaces is small.
Well yea. But so can abstract methods. That’s not the real point of using interfaces. The real point is that interfaces:
From the typing and performance levels: none – see above.
I guess, you could argue that if you use interfaces in a way that crosses the implementation hierarchy, then you have more flexibility at the client level. I guess you could call that a “benefit for polymorphism”. (By contrast, if your interface hierarchy exactly mirrors your implementation class hierarchy, then you’ve probably not achieved anything … at least in terms of the code as written.)
However, polymorphism is a means to an end, not a goal in its own right, so I would argue that asking about “benefits for polymorphism” in an abstract sense is missing the point. The real point is designing and implementing programs in a way that makes sense, and results in maintainable code.