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?
3 Answers
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.
1 Comment
Dois
What about: public interface I { public void hey(); } public class X { public void hey() { /*...*/ } public class A extends X implements I { } Does this work?
- 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.
1 Comment
delfuego
+1 just for the "why don't you try it before asking?" point -- something well worth conveying more regularly.
- No, interfaces must be explicitly implemented.
- Interfaces implemented by base classes are by extension always implemented by derived classes.
1 Comment
trashgod
As a corollary, an abstract class that implements an interface may defer the implementation to a concrete subclass: java.sun.com/docs/books/tutorial/java/IandI/abstract.html