[英]Generic instance variable in abstract class
我想创建强制子类声明变量的父/抽象类。
例如我有 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>
}
我尝试了多种方法,但没有奏效。
关于如何实现这一目标的任何想法?
你可以这样做:
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);
}
}
您不能使用这样的泛型来声明变量。
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
覆盖它们,返回的值将分配给您的字段。
您可以在 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.