我以Account的名称创建了一个类。然后,我将实例化类型类的对象。所有代码都保存在文件TestAccount中。但是系统给我一个错误,如下所示


线程“主”中的异常java.lang.ExceptionInInitializerError
在testaccount.TestAccount.main(TestAccount.java:8)
引起原因:java.lang.RuntimeException:无法编译的源代码-类Account是公共的,应在名为Account.java的文件中声明
在testaccount.Account。(TestAccount.java:20)
...还有1个
Java结果: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的新文件,然后在其中放置帐户类。这是因为当您从另一个类调用帐户时,JVM将去寻找Account.class,如果您的帐户类在名为TestAccount.class的文件中,它将无法找到它。

否则,编译器将不会编译您的文件

只要您的两个类都在同一个程序包(文件夹)中,就不必为“链接”这两者而做任何特殊的事情。

当然,除非要嵌套类,否则将Account类放在TestAccount类中。尽管我不建议这样做,因为它很混乱。

10-08 20:25