简体   繁体   中英

Java Generics extends

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){
...
}

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 :-).

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>());

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM