Imagine the following code:
class A {}
class B extends A {}
interface IA extends Iterable<A> {}
interface IB extends Iterable<B> {}
Ideally, I would like the interface IB
to be able to also extend IA
because it does in fact allow you to retrieve A
s.
interface IB extends Iterable<B>, IA {}
or even
interface IB extends Iterable<B> implements IA {}
However, the compiler really dislikes both of those and it would make my code much better if this was allowed as conceptually B can be used as A without up-casting everywhere
What solutions are available for me to solve this problem?
Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class.
Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.
Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.
An Interface is not a superclass because a class can only have one superclass but implement multiple Interfaces.
The non-covariance of generics means that what you want isn't viable (at least not in the general case).
However, perhaps wildcards would solve your specific problem? e.g.
void methodThatOperatesOnA(Iterable<? extends A> it) {
...
}
This will allow you to extract elements from it
as if they were A
s, but the compiler will prevent you from inserting objects,* because it can't guarantee that invariants would be maintained.
null
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