[英]Calling methods with objects trouble
因此,我需要在部分作業中這樣做:
創建一個名為Customer類的方法hasMoreMoneyThan(Customer c)
返回true
,如果客戶調用該方法具有比客戶更多的錢c
,否則應該返回false
。
我希望為“客戶調用方法”這一行指出正確的方向
這對我來說很混亂,沒有任何意義,這是我的Customer
所在的類。
這是必要的代碼:
public class Customer
{
private String name;
private int age;
private float money;
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Customer(String n, int a, float m)
{
name = n;
age = a;
money = m;
}
我開始編寫該方法:
public boolean hasMoreMoneyThan(Customer c)
{
}
但是我不確定如何用我的Customer
對象(我認為這個問題是在問這個)來調用它。
其他相關代碼:
public class StoreTestProgram {
public static void main(String args[]) {
Customer[] result;
Store walmart;
walmart = new Store("Walmart off Innes");
walmart.addCustomer(new Customer("Amie", 14, 100));
}
}
在對象上調用方法時,對象變量在當前范圍內。 在這種情況下,“調用方法的客戶”是調用該方法的對象(該對象是類的實例)。
因此,如果在Customer a
上調用boolean hasMoreMoneyThan(Customer c)
,那么您應該認為它是在問Customer a has more money than Customer c?
。
您可以使用this
關鍵字引用當前對象(以幫助讀者區別於Customer c
)。
因此,在您的hasMoreMoneyThan
方法中,可以將this.money
與c.money
進行比較。
要調用此方法,您需要引用當前客戶和要與之進行比較的客戶。 您可以執行以下操作:
Customer currentCustomer = new Customer(...
Customer customerToCompareWith = new Customer(...
if (currentCustomer.hasMoreMoneyThan(customerToCompareWith)) {
// do something
}
編輯讓我們嘗試另一個示例。 假設您想要一種方法來知道一個客戶是否比另一個客戶大。 該代碼可能類似於:
public boolean isOlderThan(Customer c) {
return this.age > c.age;
}
並調用該方法:
if (currentCustomer.isOlderThan(customerToCompareWith)) {
// the current customer is older
} else {
// the current customer is not older
}
this
是您如何從屬於對象成員的方法中引用對象的方法。 this.money ><=? c.money
this.money ><=? c.money
如果在構造函數中使用了public Customer(String name, int age, float money)
,則應使用this.name= name
而不是name= n
來消除歧義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.