2015-11-03 84 views
1

我需要擴展class A,但它需要重寫它的構造函數。使用Java中的默認構造函數擴展類

package com.example.io; // Package belongs to jar from maven dependency 

public class A { 
    A(String s, Integer i) { 
     // constructor code 
    } 

    // other methods 
} 

因爲它是默認的構造函數(只包訪問一個構造函數),我不能在包外訪問,所以我在我的源代碼com.example.io創建相同的包名和擴展class A併成功建成。

package com.example.io; // Package belongs to my source code 

public class B extends A{ 
    B(String s, Integer i) { 
     super(s, i); // Throws error on runtime 
    } 

    // other methods 
} 

但它拋出運行時錯誤說 -

java.lang.IllegalAccessError: tried to access method com.example.io.A.<init>(Ljava/lang/String;Ljava/lang/Integer;)V from class com.example.io.B 

如何解決這個問題?我的意思是,有什麼辦法可以用默認構造函數來擴展A類?

+0

@ElliottFrisch編輯後'B' –

+0

您需要刪除所有的* .class文件,然後重新編譯。您的磁盤上仍舊存在舊類文件,導致此問題。 (如果這是一個「真正的」問題,那麼編譯時會出錯,而不是在運行時) –

+0

「default」是什麼意思?你的意思是一個包訪問的構造函數嗎?或者你的意思是默認的無參數構造函數? – dantiston

回答

1

您絕對不應該只複製第三方庫軟件包的名稱。這可能會導致意想不到的結果。請參閱this answer

相反,如果該類是public,則應該創建自己的子類並定義自己的構造函數。如果超類的構造函數設置爲打包,則不能調用它。在這種情況下,如果你的代碼,你可以重新實現必要的構造措施需要:

public class MyClass extends A { 

    String myString; 
    Integer myInteger; 
    String myField; 

    MyClass(String s, Integer i) { 
     // Can't do this because it's set to package 
     // super(s, i); 
     // Re-implement? 
     this.myString = s; 
     this.myInteger = i; 
     // Implement your own stuff 
     this.myField = s + String.valueOf(i); 
    } 
}