抽象类中的通用实例变量

时间:2018-09-05 13:58:52

标签: java oop generics inheritance abstract

我想使父类/抽象类强制子类声明变量。

例如 我有2个抽象类

public abstract class Key {  <something> }
public abstract class Value { <something> }

现在为以上创建子级。

public class ChildKey extends Key { <something> }
public class ChildValue extends Value { <something> }

我想创建一个看起来像这样的Result类

public abstract class Result {
 protected <T extends Key> key;
 protected <T extends Value> value;
}

以便我可以创建

之类的Result子级
public class ChildResult extends Result {
 public ChildKey key; // this should be forcible
 public ChildValue value; // Same as above
 <some method>
}

我尝试了多种方法,但是没有用。

关于如何实现此目标的任何想法?

3 个答案:

答案 0 :(得分:1)

您可以这样做:

public abstract class Key {
}

public abstract class Value {
}

public class ChildKey extends Key {

}
public class ChildValue extends Value {

}

public abstract class Result<K extends Key, V extends Value> {
    protected final K key;
    protected final V value;

    protected Result(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

public class ChildResult extends Result<ChildKey, ChildValue> {

    public ChildResult(ChildKey key, ChildValue value) {
        super(key, value);
    }
}

答案 1 :(得分:0)

您不能使用类似的泛型来声明变量。

public abstract class Result {
    protected Key key;
    protected Value value;


    public Result(){
        key = giveKey();
        value = giveValue();
    }

    public abstract Key giveKey();
    public abstract Value giveValue();
}

您将不得不在ChildResult中覆盖它们,返回的值将分配给您的字段。

答案 2 :(得分:0)

您可以在Result类上强制使用属性:

public abstract class Value {}
public abstract class Key {}
public class ChildValue extends Value {}
public class ChildKey extends Key {}
// use type parameters and force attributes in your abstract class of result
public abstract class Result<K extends Key, V extends Value> {
  protected K key;
  protected V value;

  public List<String> fetchResult() {
      return new ArrayList<>();
  }
}

并像这样使用它:

public class Main {
  public static void main(String[] args) {
      Result result = new Result<ChildKey,ChildValue>(){};
      result.fetchResult();
  }
}