In Java people often define an interface together with a class and use interface name instead of class name where possible, in order to allow new implementations later. Here the logical interface is duplicated.
This kind of "just in case" duplication would not be necessary if Java allowed using a class as an interface eg: class MyScanner extends MyStuff implements java.util.Scanner
. Also this would ease the situation where I need to provide a class-type but I don't want to extend that class.
As I understand, "implementing a class" would be rejected not only by the compiler but also by the JVM (if I hacked this declaration into classfile). Are there some technical difficulties for this or it's not regarded as important thing? It doesn't look like a backward-compatiblity problem (I mean, old code would run fine if JVM supported this).
EDIT: for clarification, I will copy here StriplingWarrior's much better wording of the same questions:
Why can't a class "implement" another class's method contract without actually extending that class? Is it a technical issue? Would it somehow open us up to some issues that the OP can't foresee?
Do I understant correctly that MyClass implements AClass
would mean that MyClass
must provide (or inherit) implementations for all public methods that AClass
has? I.e. each class implicitly defines an interface consisting of its public methods?
If so, then the problem I see with that is that interfaces are really something very different from classes, and the two should not be mixed like that. Interfaces define a contract, classes an implementation. A consequence of that: The functionality of classes can be extended relatively freely, but not so interfaces with existing implementations.
So there you have a very concrete reason why your suggestion would be bad: you could never add any public method to any class without risking to break some code that implements
that class.
And on the other hand, what problems would it solve? The code duplication when you have an interface with a single implementation? How about solving that by not doing it? IMO it's usually something done by people doing TDD dogmatically while using outdated mocking frameworks not capable of mocking concrete classes.