![](/img/trans.png)
[英]Partial access from class type variable that points at an instance of a specialized type
[英]How to access an instance of Class A by a mutual variable type in Class B
我正在嘗試在BankAccount
類中編寫一種方法,該方法僅使用兩個參數即User
類型的“ user”字段(這是一個包含String username
和String password
以及ArrayList<String> usernames
的類)從帳戶中提取資金的方法ArrayList<String> usernames
),以及類型為double的“ amount”字段。
BankAccount
類具有類型為User的accountOwner
字段和類型為double
的availableFunds
字段。 我試圖找出如何通過類型為User
的用戶參數查找/訪問BankAccount
類的實例。
我是Java的新手,我不明白如何僅通過用戶類型變量來調用“ BankAccount”的實例。
我嘗試創建一個新的BankAccount
實例,但是我不想這樣做,因為我試圖訪問一個已經存在的BankAccount
實例。
以下是User類的相關方法和字段:
public class User {
static ArrayList<String> usernames = new ArrayList<String>();
private String username;
private String password;
public String getUsername()
{
return username;
}
BankAccount類:
public class BankAccount {
private User accountOwner;
private double availableFunds;
public double getFunds()
{
return availableFunds;
}
public void deposit(double deposit)
{
availableFunds += deposit;
}
這是我必須嘗試編寫的方法:
public void withdraw(User user, double withdrawal) throws UserException, FundsException
{
}
基本上,用戶輸入了User用戶並提取了兩倍的提款額,我必須從以某種方式使用User用戶引用的BankAccount類中扣除提款額。
那么,您需要映射您傳遞給銀行帳戶的用戶。 為此,可以使用用戶名作為映射鍵,例如:
Map<String, User> usersByName = new Hashmap<>();
Map<String, BankAccount> accountsByUsername = new Hashmap<>();
然后,您可以填寫地圖,例如:
BankAccount account = ...//you got it from somewhere
accountsByUsername.put( account.getUser().getUsername(), account);
提款時,您通過用戶名獲得帳戶:
BankAccount account = accountsByUsername.get(user.getUsername());
或者,您可以直接將User
用作地圖鍵,即Map<User, BankAccount>
但是您必須滿足一些要求:
User
實現equals()
和hashCode()
,它們可能僅使用username
屬性 User
正在該2種方法不可變的-地圖鍵不應該擅自改變 編輯 :
在評論中回答您的問題,如果您只有用戶名但只有Map<User, BankAccount>
或只有Collection<BankAccount>
Map<User, BankAccount>
那么如何獲得該帳戶,這里有3種可能性:
如果您有Map<User, BankAccount>
,則可以先查找用戶,即
User user = usersByName.get(username); BankAccount account = accountsByUser.get(user);
另外,您只能在User.equals()
(和User.hashCode()
)中使用username
並創建一個僅用於查找的新User
實例:
BankAccount account = accountsByUser.get(new User(username));
如果您只有Collection<BankAccount>
,則可以遍歷所有帳戶並查找與所有者的用戶名匹配的帳戶。 使用流可能看起來像這樣:
BankAccount account = accounts.stream()
.filter(a -> a.getOwner().getUsername().equals(username))
.findFirst()
.orElse(null);
看到真實的銀行帳戶開戶可視化,
1)您創建了一個用戶,(通過提交文件來驗證您的kyc)2)創建了一個銀行帳戶,並且其中一個開戶的用戶成為所有者3)您將資金存入銀行帳戶,將其提取...等
因此,現在應該從哪個提款操作中提取資金,哪個用戶正在提取資金。
現在,提現方法應該驗證用戶是否是帳戶的正確所有者
//Create banaccount and user objects seperately
public void withdraw(BankAccount banAcc , User user, double withdrawal) throws UserException, FundsException
{
if(!bankAcc.getUser()==user) {
throw new AuthenticationException("User is not authorised to withdraw funds");
}
if(bankAcc.getAvailableFunds < withdrawal) {
throw new FundsException("Insufficient funds");
}
bankAcc.setAvailableFunds(bankAcc.getAvailableFunds-withdrawal);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.