Let's say I have following interface:
interface Mammal { void marry(Mammal m); Mammal giveBirthTo(); }
However, this doesn't say quite exactly what I want.
Obviously, a human can't marry a dog, nor give birth to a cat. So how can I embed this information into the interface, such that the input type and output type can be changed automatically as it gets implemented?
An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
There is no easy way to do that. If you add a method to the interface all implementing classes must override it. If you change the interface to an abstract class then you have to refactor the implementing classes as well.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.
At present, a Java interface can have up to six different types. Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class.
You could use generics and change your design.
Something in the lines of:
interface Marriable<T extends Mammal> { void marry(T sweetHalf); T giveBirthTo(); }
... where Mammal
is your top interface or abstract class, and Human
, Dog
, Unicorn
etc. extend / implement it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With