如下例 , 只要重新new 一個AnotherCustomMathAdd物件 , 把CustomMathAdd物件換掉 , 就會
得到新的結果.
package convention;
public class CodingByInterface {
public static void main(String[] args){
CustomMathAdd cma = new CustomMathAdd();
add(cma , 1, 2);
}
public static void add(MathAdd ma , int a , int b){
System.out.println(ma.basicAdd(a, b));
}
}
interface MathAdd{
public int basicAdd(int a , int b);
public int advanceAdd(int a , int b);
}
class CustomMathAdd implements MathAdd {
public int basicAdd(int a, int b) {
return a + b;
}
public int advanceAdd(int a, int b) {
return a*2 + b;
}
}
class AnotherCustomMathAdd implements MathAdd {
public int basicAdd(int a, int b) {
return 0;
}
public int advanceAdd(int a, int b) {
return 1;
}
}
沒有留言:
張貼留言