我创建了一个名为 Account 的类。然后我实例化类型类的对象。所有代码都保存在文件 TestAccount.txt 中。但系统给我一个错误,如下所示
Exception in thread "main" java.lang.ExceptionInInitializerError at testaccount.TestAccount.main(TestAccount.java:8) Caused by: java.lang.RuntimeException: Uncompilable source code - class Account is public, should be declared in a file named Account.java at testaccount.Account.(TestAccount.java:20) ... 1 more Java Result: 1
下面是我的代码:
package testaccount;
public class TestAccount
{
public static void main(String[] args)
{
Account Account1=new Account();
Account1.setId(1122);
Account1.setBalance(20000);
Account1.setAnnualInterestRate(4.5);
System.out.println("The monthly interest rate is " + Account1.getMonthlyInterestRate());
System.out.println("The balance after the withdrawal is "+ Account1.withdraw(2000));
System.out.println("The balabce after the deposit is " + Account1.deposit(3000));
}
}
public class Account
{
private int id;
private double balance;
private double annualInterestRate;
private static long dateCreated;
public Account()
{
id=0;
balance=0;
annualInterestRate=0;
dateCreated=System.currentTimeMillis();
}
public Account(int newId,double newBalance)
{
id=newId;
balance=newBalance;
}
public int getId()
{
return id;
}
public void setId(int newId)
{
id=newId;
}
public double getbalance()
{
return balance;
}
public void setBalance(double newBalance)
{
balance=newBalance;
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public void setAnnualInterestRate(double newAnnualInterestRate)
{
annualInterestRate=newAnnualInterestRate;
}
public static long getDateCreate()
{
return dateCreated;
}
public double getMonthlyInterestRate()
{
return (annualInterestRate/12);
}
public double withdraw(double newWithdraw)
{
return (balance-newWithdraw);
}
public double deposit(double deposit)
{
return (balance+deposit);
}
}
有人可以告诉我我做错了什么吗?
最佳答案
您必须创建一个名为 Account.java
的新文件,并将您的帐户类放入其中。这是因为当您从另一个类调用 account 时,jvm 将查找 Account.class
并且如果您的 account 类位于名为 TestAccount.class
的文件中,则它不会能够找到它。
否则编译器将不会编译您的文件
只要您的两个类位于同一个包(文件夹)中,您就不必执行任何特殊操作来“链接”这两个类。
当然,除非您想要嵌套这些类,在这种情况下,您可以将 Account
类放入 TestAccount
类中。虽然我不推荐这样做,因为它很困惑。
关于java - 类无法实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19718926/