如何从同一个类中的另一个方法调用一个方法(java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35901647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:14:34  来源:igfitidea点击:

How to call a method from another method in the same class (java)

javaoopmethods

提问by Mondo192

I've been trying to understand how to call a method from inside another method of the same class by reading "Java how to program early objects".

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

I'm totally lost at the moment, the analogy used in the book makes it easy to visualise whats going on. However, translating that into code is challenging.

此刻我完全迷失了,书中使用的类比使我很容易想象正在发生的事情。但是,将其转换为代码具有挑战性。

I have tried many times to figure this out and have gotten this far: P.S.for the sake of simplicity I have excluded code that I think is not important for my question...

我已经尝试了很多次来解决这个问题并且已经走了这么远: PS为了简单起见,我排除了我认为对我的问题不重要的代码......

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
    }

Tester code:

测试代码:

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();
    }
}

What is the code to call a method inside another method? Do the values of each individual house price get called?

在另一个方法中调用一个方法的代码是什么?每个独立房价的价值会被调用吗?

回答by Charu Khurana

you could simple call calculateFees(housePrice);as the only housePricevariable visible at point of calling is instance variableprivate int housePrice;

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

Assuming you've a constructorcall to set housePricebased on how you're creating BuyAHouseInc

假设您根据您的创建方式 constructor调用了 sethousePriceBuyAHouseInc

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

//计算费用和税款的方法 public void calculateFees(int housePrice) // 是否收到 this.housePrice?{ // 做一些事情 }

Yes, this would receive housePricepassed via calculateFees(housePrice);

是的,这将housePrice通过calculateFees(housePrice);

calculateFees(int housePrice)Local variable defined above is only visible inside calculateFees(int housePrice){...}method

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

Passing Information to a Method or a Constructor

将信息传递给方法或构造函数

UPDATE:Based on comments, you'd need to update your setter to pass house price

更新:根据评论,您需要更新您的二传手以传递房价

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

        calculateFees(this.housePrice); 
    }

回答by Christopher Schneider

Yes, your assumptions are correct.

是的,你的假设是正确的。

However, there is something important to note. This code:

但是,有一些重要的事情需要注意。这段代码:

public void setHousePrice()
{
    // do stuff etc.

    calculateFees(this.housePrice); // <---This probably doesn't do what you think it does
}

// No. This doesn't receive this.housePrice. It receives the VALUE of this.housePrice. 
// It's a completely new variable
public void calculateFees(int housePrice) .
{
  // do some stuff
}

Java is pass by value. You're passing the value of housePrice, but you aren't modifying the original housePrice.

Java 是按值传递的。您正在传递 housePrice 的值,但您没有修改原始 housePrice。

So if you "do some stuff" and modify the housePrice variable passed in, those changes aren't saved unless you are setting housePrice inside calculateFees.

因此,如果您“做一些事情”并修改传入的 housePrice 变量,除非您在 calculateFees 中设置 housePrice,否则不会保存这些更改。

In a case like this, it's best to manipulate any member variables through getters/setters. Convention, by the way, is that a setter should always take a value. This isn't arbitrary, as many libraries rely on set/get methods acting a certain way.

在这种情况下,最好通过 getter/setter 操作任何成员变量。顺便说一下,约定是 setter 应该始终采用一个值。这不是任意的,因为许多库依赖于以某种方式运行的 set/get 方法。

I've edited the above answer to be more clear.

我已经编辑了上面的答案,以便更清楚。

回答by Monroy

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

    public BuyAHouseInc(double housePrice, int amountOfHouses, int houseCounter) {
        this.housePrice = housePrice;
        this.amountOfHouses = amountOfHouses;
        this.houseCounter = houseCounter;
    }

    // method that sets the house price
    public void generateHousePrice() {
        // do stuff etc.
        // you could also put the logic in the set method... Had to change the method name to 
        // generate as the getters and setter where created and the setter method is named
        // exactly like your previous method
        calculateFees(housePrice); // this is were I'm not sure...
    }

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

    public double getHousePrice() {
        return housePrice;
    }

    public void setHousePrice(double housePrice) {
        this.housePrice = housePrice;
    }

    public int getAmountOfHouses() {
        return amountOfHouses;
    }

    public void setAmountOfHouses(int amountOfHouses) {
        this.amountOfHouses = amountOfHouses;
    }

    public int getHouseCounter() {
        return houseCounter;
    }

    public void setHouseCounter(int houseCounter) {
        this.houseCounter = houseCounter;
    }

    @Override
    public String toString() {
    return "BuyAHouseInc [housePrice=" + housePrice + ", amountOfHouses=" + amountOfHouses + ", houseCounter="
            + houseCounter + "]";
}


}

Separate the two classes in different files. Another thing to point out is to use double for the price instead of int. You must also create the getters and setters to be able to get and set your properties. You must also add a constructor in the class. Then you can create an instance of the class in the main and call its methods. The main method would be something like below.

将两个类分开在不同的文件中。另一件要指出的事情是使用 double 而不是 int 来表示价格。您还必须创建 getter 和 setter 才能获取和设置您的属性。您还必须在类中添加一个构造函数。然后你可以在 main 中创建一个类的实例并调用它的方法。主要方法如下所示。

public class Main {

    public static void main(String... args) {
        BuyAHouseInc test = new BuyAHouseInc(200000, 4, 2);
        test.setAmountOfHouses(6); // changed from 4 to 6
        test.generateHousePrice();
        test.calculateFees(test.getHousePrice());
        test.toString();

    }
}

Hope you find this helpful and good luck ! I have edited the code and added the toString method to output information as a string.

希望你觉得这有帮助,祝你好运!我已经编辑了代码并添加了 toString 方法以将信息作为字符串输出。

回答by Daniel Yoon

Please correct me if I'm wrong but is this a possible solution:

如果我错了,请纠正我,但这是一个可能的解决方案:

public void setHousePrice(int price)
{


    calculateFees(price); 
}


public void calculateFees(int housePrice) 
{
  // stuff with housePrice
}

then do

然后做

variable.setHousePrice(variable.getHousePrice);