Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and interfaces

Tags:

java

generics

Having this design :

interface Foo<T> {
   void doSomething(T t);
}

class FooImpl implements Foo<Integer> {
   //code... 
}

interface Bar extends Foo {
   //code...
}

class BarImpl extends FooImpl implements Bar {
     //code...
}

It gives me Compile Error :

The interface Foo cannot be implemented more than once with different arguments: Foo and Foo

a simple fix for this issue is :

interface Bar extends Foo<Integer> {
 // code...
}

Integer type in Bar interface is totally useless.

is there any better way to solve this issue ? any better design?

Thanks for your advices.

EDIT:

given solution:

> interface Bar<T> extends Foo<T> 

is ok, but its same as my previous solution. i don't need T type in Bar.

let me give a better sample:

interface ReadOnlyEntity {
}

interface ReadWriteEntity extends ReadOnlyEntity {
}

interface ReadOnlyDAO<T extends ReadOnlyEntity> {
}

interface ReadWriteDAO<K extends ReadWriteEntity, T extends ReadonlyEntity> extends ReadOnlyDAO<T> {
}

is this a good design?

like image 703
mhshams Avatar asked Dec 28 '22 06:12

mhshams


2 Answers

I'd recommend thinking of a type for the Bar generic or rethink your design. If there's no object that makes sense for Bar, then it shouldn't be implementing Foo<T>.

EDIT:

is this a good design?

No, not in my opinion.

like image 133
duffymo Avatar answered Jan 12 '23 01:01

duffymo


interface Bar<T> extends Foo<T> {
    // code...
}

class BarImpl extends FooImpl implements Bar<Integer> {
    // code...
}

However, it would be best if we know the exact semantics of your interfaces.

like image 43
Bozho Avatar answered Jan 12 '23 02:01

Bozho