简体   繁体   English

Java 在另一个 class 中调用方法

[英]Java calling method in another class

I am trying to create a Java class with certain number of pizzas that decreases in number我正在尝试创建一个 Java class 具有一定数量的比萨饼数量减少

if someone steals it.如果有人偷了它。

I have two classes.我有两节课。

class House where pizza is, class 比萨是的房子,

public class House {
    private static int totalPizzas;

    public House() {
        totalPizzas = totalPizzas;
    }

    public int getTotalPizzas() {
        return totalPizzas;
    }

    public static void setTotalPizzas(int totalPizzas) {
        totalPizzas = totalPizzas - Thief.stealPizza(House stolenPizza);
    }    
}

and class Thief that steals the pizza.和 class 偷披萨的小偷。

public class Thief {
    private String name;
    private int age;

    public Thief() {
        name = "abc";
        age = 11;
    }

    public static void stealPizza(House stolenPizza) {
        ??????? 
    }   
} 

My main concern is the???????我最关心的是?????? part where I feel like I should set stolenPizza to certain我觉得我应该将被盗披萨设置为确定的部分

integers but整数但是

stolenPizza = 1;

certainly does not work.肯定不行。

Could someone give me a bit of advice on how I should approach this?有人可以就我应该如何处理这个问题给我一些建议吗?

Thank you very much for reading.非常感谢您的阅读。

One way to do it would be to do something like:一种方法是执行以下操作:

 public class Thief {
        private String name;
        private int age;

        public Thief() {
            name = "abc";
            age = 11;
        }

        public static void stealPizza() {
           House.setTotalPizzas(House.totalPizzas - 1);
        }   
    }


public class House {
   private static int totalPizzas;

   public House() {
       totalPizzas = totalPizzas;
   }

   public int getTotalPizzas() {
       return totalPizzas;
   }

   public static void setTotalPizzas(int totalPizzas) {
       House.totalPizzas = totalPizzas;
   }    
}

Your constructor is missing something if I understand your code right:如果我正确理解您的代码,您的构造函数会丢失一些东西:

Your code你的代码

 public House() {
            totalPizzas = totalPizzas;
 }

will set the amount of totalPizzas on itself without assigning any "real" integer value to it.将自行设置 totalPizzas 的数量,而不为其分配任何“真实” integer 值。 Try尝试

 public House(int totalPizzas) {
            totalPizzas = totalPizzas;
 }

so that you actually can assign a number of Pizzas to the house when calling the constructor, for example:这样您实际上可以在调用构造函数时为房子分配一些比萨饼,例如:

House house = new House (12);

if you want to have 12 Pizzas in the house.如果你想在家里有 12 个披萨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM