简体   繁体   English

Java泛型扩展

[英]Java Generics extends

Let's have two classes in Java (7): 让我们在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. Java不支持多重继承,因此每个类只能扩展一个类。 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 :-). 但是显然,现在AB本身分别不是HashMapTreeMap子类,因此如果您需要它,那您就不走运了:-)。

As they both implement Map<T,T> you can do something like: 当它们都实现Map<T,T>您可以执行以下操作:

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. 我认为您应该使用所需的方法创建一个Abstract类。 And then instead os extends HashMap and TreeMap, use this data structures as fields of your new classes depending on your needs. 然后,OS扩展了HashMap和TreeMap,请根据需要将此数据结构用作新类的字段。

For instance: 例如:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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