我真的很喜欢使用初始化程序来使构造和配置类更容易理解。基本上我更喜欢这样:
new ClassObj().StartingFrom(1).EndingAt(5).IncrementBy(1).Backwards();
而不是这样:
new ClassObj(1,5,1,false);
当Java与继承混合在一起时,这有点麻烦,因为返回类型默认为尽可能通用。我发现了使用自引用继承(Java:在超类方法签名中返回子类)的可行解决方案,但是我遇到了一些问题。
我的问题是Parent类实现Iterable,但是通用类型参数丢失了,因此for-each循环想返回一个Object而不是File。
这是一个显示行为的SSCCE:
public class SSCCE {
private static abstract class Sentence<T extends Sentence<T>> implements Iterable<String> {
protected LinkedList<String> Words = new LinkedList<>();
abstract T self();
public T Say(String word) {
Words.add(word);
return self();
}
@Override
public Iterator<String> iterator () {
return Words.iterator();
}
}
static class QuietSentence extends Sentence<QuietSentence> {
public QuietSentence Whisper(String word) {
Say(word.toLowerCase());
return this;
}
@Override
QuietSentence self() {
return this;
}
}
static class LoudSentence extends Sentence<LoudSentence> {
public LoudSentence Shout(String word) {
return Say(word.toUpperCase());
}
@Override
LoudSentence self() {
return this;
}
}
static void PrintWords(Sentence words) {
for(Object obj : words) {
// I'd really like to avoid this cast
String word = (String)obj;
System.out.println(new StringBuilder(word).append(": ").append(word.length())
.toString());
}
}
public static void main (String[] args) {
QuietSentence peaceful_words = new QuietSentence().Say("Hello").Whisper("World");
PrintWords(peaceful_words);
LoudSentence noisy_words = new LoudSentence().Say("Hello").Shout("World");
PrintWords(noisy_words);
}
}
怎么回事,我该如何解决?
因此,事实证明问题出在我没有正确指定类型。该PrintWords
功能的最小修复可以解决该问题。
static void PrintWords(Sentence<? extends Sentence> words) {
for(String word : words) {
System.out.println(new StringBuilder(word).append(": ").append(word.length())
.toString());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句