我一直在尝试通过阅读“ Java如何编程早期对象”来理解如何从同一个类的另一个方法内部调用一个方法。

此刻我完全迷失了,这本书中使用的类比可以使可视化变得容易。但是,将其转换为代码具有挑战性。

我已经尝试了很多次以弄清楚这一点,并且到目前为止:
附言为了简单起见,我排除了我认为对我的问题不重要的代码...

import java.util.Scanner;

public class BuyAHouseInc
{
    private int housePrice;
    private int amountOfHouses;
    private int houseCounter;

    // method to enter the amount of houses on sale
    public void setAmountOfHouses()
    {
        // do stuff etc.
    }

    // method that sets the house price
    public void setHousePrice()
    {
        // do stuff etc.

        calculateFees(this.housePrice); // this is where I'm not sure...
    }

    //method to calculate fees and taxes
    public void calculateFees(int housePrice) // does this receive this.housePrice?
    {
      // do some stuff
    }


测试人员代码:

public class BuyAHouseIncTester
{
    public static void main(String[] args)
    {
        BuyAHouseInc client1 = new BuyAHouseInc("John","Doyle","15 Newton Drive\nDublin 5\n", 550000) // Create object
        // set amount of houses on sale to client 1
        client1.setAmountOfHouses();

        // set house price for each of the houses added to database
        client1.setHousePrice();
    }
}


在另一个方法中调用一个方法的代码是什么?是否会调用每个房屋价格的值?

最佳答案

您可以简单地调用calculateFees(housePrice);,因为在调用时唯一可见的housePrice变量是instance variable private int housePrice;

假设您有一个constructor调用根据您创建housePrice的方式设置BuyAHouseInc


  //计算费用和税金的方法
      公共无效的calculateFees(int housePrice)//是否收到this.housePrice?
      {
        //做一些事情
      }


是的,这将收到通过housePrice传递的calculateFees(housePrice);

calculateFees(int housePrice)
上面定义的局部变量仅在calculateFees(int housePrice){...}方法内部可见

Passing Information to a Method or a Constructor

更新:根据评论,您需要更新您的设置员以通过房价

public void setHousePrice(int housePrice)
    {
        this.housePrice = housePrice;

        calculateFees(this.housePrice);
    }

08-05 20:27