【问题标题】:Using 'this' keyword in a class with a no arg (default constructor) in Java?在Java中没有arg(默认构造函数)的类中使用'this'关键字?
【发布时间】: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

标签: java this


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    首先,什么是java中的“this”关键字?

    From oracle java docs:

    在实例方法或构造函数中使用 this 关键字,这是对当前对象的引用 - 正在调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

    所以说到你的问题,你的构造函数不需要被参数化来使用this。您也可以将 this 关键字与默认构造函数一起使用。

    基本上你只需要记住“this关键字指的是方法或构造函数中的当前对象。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 2012-04-15
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2021-06-09
      相关资源
      最近更新 更多