Bluej基础知识 - 测试员类

时间:2015-10-21 19:52:37

标签: oop

我制造了一种将钱从物体转移到另一物体的方法 这主要是为了创建一个模拟测试者类的类来执行以下操作

public class BankAccountTest
     {
     public void main()
     {
     // Create an account with an opening balance of 5000 AED for Mr. Said
     BankAccount acc1 = new BankAccount("Said", 5000);
     acc1.withdraw(1000);
     acc1.printAccountInfo(); // Should display on the screen: "Said's blanace is 4000"
    // Create an accoutn with an initial balance of ZERO for Mr. Shady
     BankAccount acc2 = new BankAccount("Shady");
     acc2.deposit(2000);

    // Transfer 3000 from acc2 to acc1. If successful, the method returns 0, otherwise -1
     int code = acc2.transfer(acc1, 3000);
     if(code !=0) {
     System.out.println("Insufficient Fund!");
     }

    System.our.println(acc1.balance() );
     System.our.println(acc2.balance() );
     }
     }

所以这是我的代码

public class BankAccount
    {
      public int balance;
      private int deposite;
      private int withdraw;
      private String name;


        public BankAccount(String name)
        { balance = 5000;

      }
       public BankAccount(String nameName, int balance)
       {
         name = nameName;
         this.balance = balance;
         deposite = 0;
         withdraw = 0;
        }
       public void DepostieMoney (int deposite)
       { this.balance = balance + deposite;}
       public void WithdrawMoney(int withdraw)
       { this.balance = balance - withdraw;

       }
       public void printAccountInfo()
       {
        System.out.println(this.name + "'s balance is " + balance);
       }
       public void TransferMoney(BankAccount that , int balance)
       { this.balance= this.balance - balance;

    }  
        }

我无法想象的是如何使下面的方法将第一个对象的项目传递给第二个对象

public void TransferMoney(BankAccount that , int balance)
   { this.balance= this.balance - balance;

那么我实际上如何为特定对象指定方法?。

  

编辑了withdrawMoney方法

public void withdrawMoney(int balance)
    {if ( balance <= this.balance)
     this.balance = this.balance - balance;
     else
     {System.out.println("insfufficient funds");} 
    } 

1 个答案:

答案 0 :(得分:0)

首先,Java编码风格表明:

  

方法应该是动词,在第一个字母的大小写混合的情况下   小写,每个内部单词的首字母大写(例如run(); runFast(); getBackground();)

现在,对于您的问题,您正在尝试将资金从一个帐户转移到另一个帐户,因此调用一个对象的方法应调用第二个对象以完成事务。

public void transferMoney(BankAccount that , int balance)
   { 
     //sanity check here
     if (this == that || that == null)
         return;

      If (withdrawMoney(balance)) {
          that.depositeMoney(balance);
      }
   }

如你所见,我选择不直接使用变量,而是通过方法。原因是围绕该方法的逻辑可能不仅仅是更新变量,例如您可能想要打印该操作。这样您只需要更新方法中的代码,transferMoney方法将保持不变。