Java 基礎之巧用Object類作為函式引數
阿新 • • 發佈:2019-02-10
看一個小例子
public class Base { public void showMessage() { System.out.println("this is Base"); } } public class A extends Base { public void showMessage() { System.out.println("this is A"); } } public class B extends Base { public void showMessage() { System.out.println("this is B"); } }
可以看到每一字繼承Base類的子類如果都需要showMessage這個函式,但是卻每個都重寫了一遍這個函式,無疑就是程式碼冗餘
可以這樣改:
public class Base { public static void showMessage(Object obj) { if(obj instanceof A) { System.out.println("this is A"); } if(obj instanceof B) { System.out.println("this is B"); } } } public class A extends Base { } public class B extends Base { public static void main(String[] args) { B b=new B(); A a=new A(); Base.showMessage(a); Base.showMessage(b); } }
執行結果: