Java Generics extends

366 views Asked by At

Let's have two classes in Java (7):

public class A<T> extends HashMap<T, T>{
...
}

and

public class B<T> extends TreeMap<T, T>{
...
}

Is it possible to have a common base class which these two classes would extend?

Thanks.

Clarification: I want that the classes share the same method

public T f(T o){
...
}
3

There are 3 answers

0
Hoopje On BEST ANSWER

No, that is not possible. Java does not support multiple inheritence, so each class can only extend a single class. Since both of your classes already extends a different class, you cannot create a class that is a superclass of both of your classes.

A possible solution is to use composition:

public class MyMap<T> extends AbstractMap<T,T> {
    private Map<T,T> delegate;

    public MyMap(Map<T,T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
    }

    public Set<Map.Entry<T,T>> entrySet() {
        return delegate.entrySet();
    }

    // Optionally, implement other Map methods by calling the same methods
    // on delegate.

    public T f(T o) {
        // ...
    }
}

and then:

public class A<T> extends MyMap<T> {
    public A() {
        super(new HashMap<>());
    }
}
public class B<T> extends MyMap<T> {
    public B() {
        super(new TreeMap<>());
    }
}

or simply:

Map<T,T> aMap = new MyMap<>(new SomeOtherMapImplementation(...));

But obviously, now A and B are not themselves subclasses of HashMap and TreeMap respectively, so if that's what you need, you're out of luck :-).

1
OldCurmudgeon On

As they both implement Map<T,T> you can do something like:

public class A<T> extends HashMap<T, T> {
}

public class B<T> extends TreeMap<T, T> {
}

List<Map<String,String>> list = Arrays.asList(new A<String>(), new B<String>());
0
Felipe Moraes On

I think you should create an Abstract class with the method that you want. And then instead os extends HashMap and TreeMap, use this data structures as fields of your new classes depending on your needs.

For instance:

public abstract class MyClass<T> {
   public T f(T o){
       ...
   }
}

public class A<T> extends MyClass<T> {
    private Map<T,T> mapThatINeed;
}