3 ms·
Often times, there is a third choice: polymorphism using interfaces. Consider an example from the article: public static void testIfElse(int jumpLabel) { if
by larryfreeman 17y ago
Often times, there is a third choice: polymorphism using interfaces.
Consider an example from the article:
public static void testIfElse(int jumpLabel) {
if(1 == jumpLabel) {
System.out.println("1");
} else if(2 == jumpLabel) {
System.out.println("2");
} else if(3 == jumpLabel) {
System.out.println("3");
} else if(4 == jumpLabel) {
System.out.println("4");
}
// Removed for simplicity
else {
System.out.println("default");
}
}
Why not implement this as follows:
public interface IfElse {
public void testIfElse();
}
public class JumpLabelDefault implements IfElse {
public void testIfElse() {
System.out.println("Default");
}
}
public class JumpLabel1 implements IfElse {
public void testIfElse() {
System.out.println("1");
}
}
...
Then, to do the same test, you have this function:
public static void testIfElse(IfElse obj) {
obj.testIfElse();
}
This is faster than either an if-else statement or a switch statement and you can easily add new cases by creating new objects without needing to change the previous code.
I'm not sure why this option is not included in the article.