【问题标题】:Need help understanding specific unresolved compilation error [duplicate]需要帮助了解特定未解决的编译错误[重复]
【发布时间】:2015-07-06 10:24:56
【问题描述】:

我需要的程序是创建一个带有帐户类的测试帐户程序。这是我想出的:

package accounts;

import java.util.Date;

public class TestAccount {


public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Date date = new java.util.Date();



Account firstaccount = new Account (1111, 10000.00, 0.045);

System.out.println("Transaction started: " + date.toString());

System.out.println("User's ID is: " + firstaccount.getId());

System.out.println("User's balance is: " + firstaccount.getBalance());

System.out.println("The montlhly interest rate is: " + firstaccount.getMonthlyInterestRate());

System.out.println("Balance after withdraw is: " + firstaccount.withdraw(1000));

System.out.println("Balance after deposit is: " + firstaccount.deposit(3000));

System.out.println("Transaction complete."); }


class Account {



private int id = 0;

private double balance = 0.0;

private double annualInterestRate = 0.0; 


public Account (int newId, double newBalance, double newAnnualInterestRate) {

id = newId;

balance = newBalance;

annualInterestRate = newAnnualInterestRate;
}

public int getId() {

return id;
}

public double getBalance () {

return balance;
}

public double getAnnualInterestRate () {

return annualInterestRate;
}

public double getMonthlyInterestRate () {

return annualInterestRate/12;
}

public double withdraw (double value) {

return balance -= value;
}

public double deposit (double value) {

return balance += value;
}

public void setId (int newId) {

id = newId;
}

public void setBalance (double newBalance) {

balance = newBalance;
}

public void setAnnualInterestRate (double newAnnualInterestRate) {

annualInterestRate = newAnnualInterestRate;
}

} 

}

这是我得到的错误:

线程“main”java.lang.Error 中的异常:未解决的编译问题: 无法访问 TestAccount 类型的封闭实例。必须使用 TestAccount 类型的封闭实例来限定分配(例如 x.new A(),其中 x 是 TestAccount 的实例)。

在accounts.TestAccount.main(TestAccount.java:12)

请帮助我了解我需要做什么。谢谢。

【问题讨论】:

    标签: java eclipse


    【解决方案1】:

    你有一个嵌套类。在 java 中,当非静态类嵌套在非静态类中时,new 语句需要像错误消息所说的那样:

    TestAccount ta = new TestAccount();
    TestAccount.Account ta_a = ta.new Account();
    

    语法很丑,再买一次 - 嵌套类也是如此。

    请参阅documentation 了解更多信息。

    希望这会有所帮助。

    【讨论】:

    • 它通过使用 Account firstaccount = new TestAccount().new Account() 工作。
    猜你喜欢
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多