题目描述
各位大神好,我嘗試用繼承和泛型的方式做一個等比數列,但是,綠色線旁框住的代碼卻一直顯示和Long不符,我有改過 protected long nextValue()方法中的long改成Long,但是這樣會變成型態不符,邏輯上也有些問題,有改和不改都會出問題,想請問大神們,到底是哪裡出錯了?需要您幫忙提點QAQ謝謝
相关代码
import java.util.*;
import java.lang.*;
public class ProgressionGeneric <k> {
protected k a;
protected k b;
ProgressionGeneric(){a=b;};
protected k firstValue (){b=a;
return b;};
protected k nextValue(){return b;};
protected void printProgression(int n){
k cc=nextValue();
System.out.print(cc+" ");
for(int i=1;i<n;i++){
k c=nextValue();
System.out.print(c+" ");
}
};
public class GeomProgression extends ProgressionGeneric<Long>{
protected long r;
GeomProgression(){ //first =1, r =1 by default
this(1,1); //first = 1; r = 1;
}
GeomProgression(long a, long base) { //Set r to base
a = a;
r = base;
}
protected long nextValue(){ long b=a; b *= r; //cur = cur*r; return b; }
}
public class Main {
public static void main(String[] args) {
GeomProgression gogo =new GeomProgression(1,4);
gogo.printProgression(3);
}
把你的程式碼貼到IDE之後修改了一下,將nextValue的返回值型態改成Long之後並沒有出現型態不符合的問題
反倒是執行的時候拋出NullPointerException,仔細看了一下,原因在於GeomProgression的建構子這邊,
你把參數a賦值給從ProgressionGeneric繼承下來的資料成員a,然而因為兩個參數都名為a,編譯器分不清誰是誰,
所以這邊賦值操作無效。
a的值就相當於null(至於為甚麼不是0,因為他不是基本型態的long,而是Long,若是沒有指定值,則預設為null)
程式運行的時候就會拋出NPE,這點需要注意一下。