TLDR
TLDR

Reputation: 33

Inheritance of Interface implementation in Java

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?

Upvotes: 3

Views: 3071

Answers (3)

Chris Kannon
Chris Kannon

Reputation: 6101

  1. No, interfaces must be explicitly implemented.
  2. Interfaces implemented by base classes are by extension always implemented by derived classes.

Upvotes: 0

duffymo
duffymo

Reputation: 309008

  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.

Upvotes: 2

ZoogieZork
ZoogieZork

Reputation: 11289

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.

Upvotes: 16

Related Questions