Thursday, 29 August 2019

java generic method


stop using Object as the type, please use generic type.


what is generic method
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html


how to override a generic method  (generic method in a interface)
http://www.java2s.com/Code/Java/Generics/Overridingagenericmethodinagenericclass.htm


you can define a generic method and define the generic type in two places (on the method or the interface)
public interface SexRule {
public Timetable getTimeTable();
public <T> String calculateDeadline(T transObj);


}

public interface SexRule<T> {
public Timetable getTimeTable();
public String calculateDeadline(T transObj);


}



Then when you override it, you need:


for the type is on the method:

same way as you are defining in the interface, you just need to "override" the generic type on the type:

public abstract class ASexRule implements SexRule  {

public Timetable getTimeTable() {
return null;
}
@Override
public <OutboundSex> String calculateDeadline(OutboundSex os) {
return null;
}


}


for the type on the interface:

you need to "override" the type on the class level then you can use the type in the overirde function.
public abstract class ASexRule<OutboundSex> implements SexRule < OutboundSex > {

public Timetable getTimeTable() {
return null;
}
@Override
public String calculateDeadline(OutboundSex os) {
return null;
}


}



No comments:

Post a comment