Correct usage of "<T extends SuperClass>"
Posted
by
yusaku
on Stack Overflow
See other posts from Stack Overflow
or by yusaku
Published on 2011-02-17T14:58:29Z
Indexed on
2011/02/17
15:25 UTC
Read the original article
Hit count: 198
I am not familiar with "Generics". Is it a correct use of "<T extends SuperClass>
" ? And do you agree that the codes after using generics are better?
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);
}
}
© Stack Overflow or respective owner