java - 在Java中没有arg(默认构造函数)的类中使用'this'关键字?
问题描述
我有一个快速的问题。我知道如何将this
Java 中的关键字与具有参数/参数的构造函数一起使用。您可以使用this
没有参数/参数的默认构造函数吗?
下面的代码示例Class BankAccount
。
我们在这个类中创建了一个方法来尽可能地退出。在该方法中,我创建了一个新BankAccount
对象来使用教授提供的测试进行测试。他不想创建account
对象,而是希望我使用this
. 如果没有包含参数/参数的构造函数,这可能吗?
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;
}
解决方案
java 关键字“this”与构造函数没有特殊的交互。它通常在构造函数中用于区分参数名称和新创建的对象的字段。
就像是
public class BankAccount {
private int accountNum;
public BankAccount() {
this.accountNum = 4;
}
}
完全有效,但多余。
java中“this”关键字的主要价值是访问更高范围内的字段,该字段已在当前范围内被屏蔽。
经典二传手示例
public void setAccountNum(int accountNum) {
this.accountNum = accountNum;
}
在这种情况下,所有对 accountNum 的引用都将引用该参数。使用“this”关键字允许我们指定要为其赋值的是对象的名为 accountNum 的字段。
推荐阅读
- crystal-reports - 水晶报表 - 将值设置为零(公式)
- python - Python标识符中的无效字符
- python - Keras AttributeError:“历史”对象没有属性“预测”
- android - 我可以在不设置谷歌地图平台计费帐户的情况下发布使用地图 SDK 的 android 应用吗?
- report - 倾城报告不显示类别 [codeceptjs]
- caching - 缓存插件不缓存
- sql - 使用 R 中的 sqlQuery 处理 SQL select 语句中的双引号
- perl - 在 Perl 中使用结构和哈希
- docker - 如何docker拉旧版本的Keycloak?
- javascript - 自动填充图像的 HTML 文件路径的 Javascript