![](/img/trans.png)
[英]How can I get an instance of a subclass of abstract class from a static method of another class?
[英]Why can't I call a method (public or static) from an Abstact class of type subclass when creating an instance of the subclass in another function?
在下面的代碼中,找不到類型為 Dollar 的函數 Dollar 並且程序無法編譯:
class Test{
abstract class Money{
protected int amount;
public Dollar dollar(int amount){
return new Dollar(amount);
}
}
class Dollar extends Money{
public Dollar(int amount){
this.amount= amount;
}
}
public void testMultiplication(){
Money d = new Money.dollar(5);
}
public static void main(String args[]){}
}
我已經使用以下命令在 cli 上啟動了我的 java 應用程序:
java File.java
以下是警告內容:
File.java:16: error: cannot find symbol
Money d = new Money.dollar(5);
^
symbol: class dollar
location: class Test.Money
1 error
error: compilation failed
該代碼引用自 Kent Beck 編寫的 Test-Driven Development By Example 一書。 還有一個 github,其中包含我用作指南的更完整的代碼: https : //github.com/No3x/money-tdd-by-example-kent-beck/blob/master/src/main/java/de /no3x/tdd/money/Money.java
我想提一下,抽象類 Money 中的函數 Dollar Dollar 也被指示為靜態的,但這會在我們正在處理的當前錯誤之上創建另一個錯誤。
閱讀上述內容后,您是否明白為什么在另一個函數中創建對象的實例時,我不能從類型為子類的 Abstact 類中調用方法(公共或靜態)?
abstract class Money
:您正在聲明一個抽象類 Money。Money d = new Money.dollar(5);
:然后您嘗試使用new
關鍵字從此類實例化一個對象。 這對於抽象類是不允許的。 如果要從外部調用抽象類中定義的方法,則它必須是static
方法,然后靜態調用此方法。 這是您的代碼的重構版本。
class Test {
abstract static class Money {
protected int amount;
public static Dollar dollar(int amount) {
return new Test().new Dollar(amount);
}
}
class Dollar extends Money {
public Dollar(int amount) {
this.amount = amount;
}
}
public void testMultiplication() {
Money d = Money.dollar(5);
}
public static void main(String args[]) {}
}
TLDR:這段代碼有很多問題,如果它是從書中復制的,那么我建議您從頭開始。 問題不在於抽象類。
問題:
首先, Money d = new Money.dollar(5);
不是有效的語法。 如果方法 A 創建了一個 B 類型的新對象,你應該寫: B justCreated = A();
(丟失new
)。
除此之外:在您的版本中(抽象類 Money 中的函數 Dollar Dollar 也被指示為 static ),由於 Dollar 是非靜態的,因此您不能使用Money.dollar()
。
如果它是靜態的,它仍然不起作用(如您所說),因為您不能在非靜態內部類中創建靜態方法,因此 Money 也必須是靜態的。 但是你不能在靜態方法中使用new
(見這個線程)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.