今天寫了下面這樣一段代碼
/*
*其中PrintView和HzPrintView是我寫的兩個類
*且HzPrintView extends PrintView
*/
PrintView printView;
if (isEnglish == true){
printView = new PrintView(psm);
}
else {
printView = new HzPrintView(psm);
}
由於這個代碼段我用了很多個地方,當時我就想能不能用方法包裝起來,直接調用。下面是我的錯誤思路:
首先我想到的是把對象引用變量作爲參數傳進方法,然後在方法中實例化,仔細一想,不行!!!如果我把它作爲參數傳進方法中,根據java參數是傳值的機制,傳進去的是對象引用變量的地址(此時爲NULL),然後在方法中實例化後,方法裏面的引用地址改變了,而方法外的並沒有改變,沒有達到目的。
然後,我又想可不可以return一個對象出來。這個時候有兩種可能情況,一種是return一個PrintView對象,另一種是return一個HzPrintView對象。怎麼做?用多態?根據經驗,先來個小的demo試試可行性。
package Demo;
public class TestDemo {
public static void main(String[] args) {
TestClass1 t;
t = test(2);
System.out.println(t.getI());
System.out.println(t.getJ); //這裏報錯,無getJ方法
}
public static TestClass1 test(int flag){
if (flag == 1){
return new TestClass1();
}
else {
return new TestClass2();
}
}
}
class TestClass1{
private int i;
public int getI() {
return i;
}
TestClass1(){
i=1;
}
}
class TestClass2 extends TestClass1{
private int j;
public int getJ() {
return j;
}
TestClass2(){
j=2;
}
}
如上代碼,寫到t.getJ的時候報錯了,說無getJ()方法。哦,對了。繼承向上轉型後子類後面添加的一些成員是用父類引用無法調用的,這個想法就此破產。
到底該怎麼搞了?後面想到或者請教到了方法會在下面進行更新,同時也希望各位有好的方法評論在下方一起學習。
如果有什麼寫的不對的地方還請各位多多指正。