我有以下进阶类(class):
/** 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(无论如何),但 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();
}
}
关于java - 如何在 java 中将 Progression 类重新设计为抽象和通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28739915/