views:

105

answers:

3

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
+2  A: 
  1. It you mean "Can it satisfy the Liskov substitution principle?", the answer is "no".
  2. 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
+1 just for the "why don't you try it before asking?" point -- something well worth conveying more regularly.
delfuego
A: 
  1. No, interfaces must be explicitly implemented.
  2. Interfaces implemented by base classes are by extension always implemented by derived classes.
Chris Kannon
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