[英]How to redesign a Progression class to be abstract and generic in java?
我有以下Progression类:
/** Generates a simple progression. By default: 0,1,2,3...*/
public class Progression {
// instance variable
protected long current;
/** Constructs a progression starting at zero. */
public Progression() { this(0); }
/** Constructs a progression with a given start value. */
public Progression(long start) { current = start; }
/** Returns the next value of the progression.*/
public long nextValue() {
long answer = current;
advance();
return answer;
}
/** Advances the current value to the next value of the progression */
protected void advance() {
current++;
}
/** Prints the next value of the progression, separated by spaces .*/
public void printProgression(int n) {
System.out.print(nextValue());
for(int j = 1; j < n;j++)
System.out.print(" " + nextValue());
System.out.println();
}
}
如何将上面的Java Progression类重新设计为抽象和泛型,生成一系列通用类型T的值,并支持一个接受初始值的构造函数?
我理解如何使上面的类抽象,但我没有看到或理解如何将类转换为泛型。 特别是我不知道如何重新设计advance()方法,以便它使用java泛型来生成通用类型T的值序列。
您只能为所有通用实例编写您知道的内容。 其他一切都是抽象的。 这可以通过查看(添加的)方法getInitial来看出:它将为Long返回0,但是(或许)为String返回“A”。 此外,nextValue是有启发性的:它调用advance(无论如何),但是前进留给实例化的实现。
public abstract class Progression<T> {
protected T current;
public Progression() { this( getInitial()); }
protected abstract T getInitial();
public Progression(T start) { current = start; }
public T nextValue() {
T answer = current;
advance();
return answer;
}
protected abstract void advance();
public void printProgression(int n) {
System.out.print(nextValue());
for(int j = 1; j < n;j++)
System.out.print(" " + nextValue());
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.