Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Interface generic of a superclass

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 As.

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?

like image 792
LiraNuna Avatar asked Jan 18 '13 20:01

LiraNuna


People also ask

What is generic interface in Java?

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.

CAN interface have generic in Java?

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.

Can we inherit generic class in Java?

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.

Can an interface be a super class?

An Interface is not a superclass because a class can only have one superclass but implement multiple Interfaces.


1 Answers

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 As, but the compiler will prevent you from inserting objects,* because it can't guarantee that invariants would be maintained.


* other than null and a few other wacky cases
like image 148
Oliver Charlesworth Avatar answered Sep 27 '22 17:09

Oliver Charlesworth