我不熟悉」泛型「。它是否正確使用「<T extends SuperClass>
」?你是否同意使用泛型後的代碼更好?正確使用「<T extends SuperClass」「
Before using Generics
=================================================
public abstract class SuperSample {
public void getSomething(boolean isProcessA) {
doProcessX();
if(isProcessA){
doProcessY(new SubASample());
}else{
doProcessY(new SubBSample());
}
}
protected abstract void doProcessX();
protected void doProcessY(SubASample subASample) {
// Nothing to do
}
protected void doProcessY(SubBSample subBSample) {
// Nothing to do
}
}
public class SubASample extends SuperSample {
@Override
protected void doProcessX() {
System.out.println("doProcessX in SubASample");
}
@Override
protected void doProcessY(SubASample subASample) {
System.out.println("doProcessY in SubASample");
}
}
public class Sample {
public static void main(String[] args) {
SubASample subASample = new SubASample();
subASample.getSomething(true);
}
}
After using Generics
=================================================
public abstract class SuperSample {
public void getSomething(boolean isProcessA) {
doProcessX();
if(isProcessA){
doProcessY(new SubASample());
}else{
doProcessY(new SubBSample());
}
}
protected abstract void doProcessX();
protected abstract <T extends SuperSample> void doProcessY(T subSample);
}
public class SubASample extends SuperSample {
@Override
protected void doProcessX() {
System.out.println("doProcessX in SubASample");
}
@Override
protected <T extends SuperSample> void doProcessY(T subSample) {
System.out.println("doProcessY in SubASample");
}
}
public class Sample {
public static void main(String[] args) {
SubASample subASample = new SubASample();
subASample.getSomething(true);
}
}
的確,我必須在所有子類中實現該方法,如果我使用它..我會照顧情況。和CRTP技巧..我從來不知道這一點。謝謝我會檢查出來。 – zono 2011-02-17 15:33:07
`class SubA extends Super`compiles,given`class SubB extends Super ` –
irreputable
2011-02-17 16:25:55