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?

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What about: public interface I { public void hey(); } public class X { public void hey() { /*...*/ } public class A extends X implements I { } Does this work?
2
  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.

1 Comment

+1 just for the "why don't you try it before asking?" point -- something well worth conveying more regularly.
0
  1. No, interfaces must be explicitly implemented.
  2. Interfaces implemented by base classes are by extension always implemented by derived classes.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.