Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply more constraints on an interface declaration in Java?

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?

like image 571
Jason Hu Avatar asked May 13 '15 13:05

Jason Hu


People also ask

How do you extend an interface in Java?

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.

Can you add extra methods to 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.

Can we extend the interface class?

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.

How many methods can an interface declare?

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.


Video Answer


1 Answers

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.

like image 153
Mena Avatar answered Sep 18 '22 05:09

Mena