【发布时间】:2021-03-22 03:22:09
【问题描述】:
我有一个简单的问题。我知道如何在 Java 中将关键字 this 与具有参数/参数的构造函数一起使用。您可以将this 与没有参数/参数的默认构造函数一起使用吗?
下面是代码Class BankAccount 的示例。
我们在这个类中创建了一个方法来尽可能地退出。在该方法中,我创建了一个新的BankAccount 对象来测试教授提供的测试。他希望我使用this,而不是创建account 对象。如果没有包含参数/参数的构造函数,这可能吗?
public double getOrAsMuchAsPossible(double requestAmount) throws InvalidAmountException, InsufficientFundsException
{
//Declare and initialize the variable amount to be used with in the method
double amount = 0;
//Create a new BankAccount object account
BankAccount account = new BankAccount();
//Deposit money into the account
account.deposit(400);
//Try to get requestAmount
try
{
//Set the amount to the request amount and withdraw from account
amount = requestAmount;
account.withdraw(requestAmount);
}
//Catch the exception with the InsufficientFundsException
catch(InsufficientFundsException exception)
{
System.out.println("Withdrawing amount: " + amount + " that is larger than balance: " + balance + " is not allowed");
}
//If the account balance is less than the amount requested
if(account.balance<requestAmount)
{
//The amount will equal the account balance, withdraw the amount from the account
amount = account.getBalance();
account.withdraw(amount);
}
return amount;
}
【问题讨论】:
-
我不明白你的问题。您可以在 any 实例方法中使用
this(表示当前实例)... -
当你按照教授的建议去做时发生了什么?如果你还没有尝试过,为什么不呢?也就是说,您似乎还没有完全掌握
this的用法。 -
在构造函数中,如果我没记错的话,这只能在
super()之后隐式或显式使用。 -
我认为通过“使用
this”,教授意味着您可以让您的方法仅在此BankAccount(即BankAccount实例getOrAsMuchAsPossible方法被调用),而不是你为某些特殊目的创建的其他完全不同的BankAccount。