I have two questions regarding interfaces in Java. 1) If a class happens to implement all the interface methods of interface I, without declaring itself as implementing them, can it still be used as input into variables of type I? 2) Does a subclass of class A which implements interface I inherits the conformance to that interface, or should it also declare itself as implementing I?
+10
A:
If a class happens to implement all the interface methods of interface I, without declaring itself as implementing them, can it still be used as input into variables of type I?
No. What you're describing is more akin to duck typing.
Does a subclass of class A which implements interface I inherits the conformance to that interface, or should it also declare itself as implementing I?
Assuming you mean:
public class A implements I { /* ... */ }
public class B extends A { /* ... */ }
In this case, B
implements I
.
ZoogieZork
2009-12-24 18:42:19
+2
A:
- It you mean "Can it satisfy the Liskov substitution principle?", the answer is "no".
- Class B conforms to its parent and need not redeclare the interface.
The best way to answer questions like these is to experiment - try it and see.
duffymo
2009-12-24 18:42:37
+1 just for the "why don't you try it before asking?" point -- something well worth conveying more regularly.
delfuego
2009-12-24 19:51:35
A:
- No, interfaces must be explicitly implemented.
- Interfaces implemented by base classes are by extension always implemented by derived classes.
Chris Kannon
2009-12-24 18:46:59
As a corollary, an abstract class that implements an interface may defer the implementation to a concrete subclass: http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html
trashgod
2009-12-24 21:48:28