首页 > 解决方案 > 在Java中没有arg(默认构造函数)的类中使用'this'关键字?

问题描述

我有一个快速的问题。我知道如何将thisJava 中的关键字与具有参数/参数的构造函数一起使用。您可以使用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;
   }

标签: javathis

解决方案


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 的字段。


推荐阅读