如何在java中将Progression类重新设计为抽象类和泛型类?
我有以下进阶课程:如何在java中将Progression类重新设计为抽象类和泛型类?,java,Java,我有以下进阶课程: /** 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 pro
/** 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();
}
}
/**生成一个简单的进程。默认情况下:0,1,2,3*/
公开课进展{
//实例变量
保护长电流;
/**构造从零开始的级数*/
公共进程(){this(0);}
/**构造具有给定起始值的级数*/
公共进程(长启动){current=start;}
/**返回级数的下一个值*/
公共长下一个值(){
长答案=当前;
前进();
返回答案;
}
/**将当前值前进到级数的下一个值*/
受保护的无效预付款(){
电流++;
}
/**打印级数的下一个值,以空格分隔*/
公共区域(int n){
System.out.print(nextValue());
对于(int j=1;j
如何将上述java Progression类重新设计为抽象和泛型类,生成泛型类型T的值序列,并支持接受初始值的单个构造函数
我知道如何使上面的类抽象,但我看不到或不理解如何将类转换为泛型。特别是,我不知道如何重新设计advance()方法,以便它使用java泛型生成泛型类型t的值序列。您只能为所有泛型实例化编写已知的代码。其他一切都是抽象的。通过查看(添加的)getInitial方法可以看出这一点:它将长时间返回0,但(可能)字符串返回“a”。另外,nextValue很有启发性:它调用advance(无论如何),但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();
}
}
公共抽象类进程{
保护T电流;
公共进程(){this(getInitial();}
受保护的抽象T getInitial();
公共进程(T开始){current=start;}
公共T下一个值(){
T答案=电流;
前进();
返回答案;
}
受保护的抽象无效提前();
公共区域(int n){
System.out.print(nextValue());
对于(int j=1;j