我已经编程了一段时间了,我对公共(public)方法的使用有疑问。我正在开发一个自动售货机程序,我有一个私有(private)方法 setUpMachine()
来初始化游戏和设置对象。我有另一个私有(private)方法 startMachine()
启动游戏并提示用户输入。然后它将输入传递给另一个私有(private)方法 checkInput()
,该方法检查输入是否有效......但这是我遇到的与其说是“问题”不如说是问题的地方我没有正确做某事的奇怪感觉。我需要为第三个方法 checkInput()
访问第一个方法 setUpMachine()
中的对象。问题是我有很多对象(糖果、薯片、苏打水、 cookies ),将它们全部传递给检查周长似乎不对。换句话说,这样做:
checkInput(FoodType candy, FoodType chips, FoodType soda, FoodType cookie)
好像不太对。这是否意味着,如果我使用私有(private)方法,每次我想使用它们时都必须传递对象?我读到公开方法是不好的做法。
对此的解释会很好,与其说是告诉我我的编码效率低下的解释,不如说是描述何时和如何使用私有(private)方法的解释,或者是否有其他方法可以做到这一点。
最佳答案
如果不想传递对象,可以将它们配置为实例变量:
public class VendingMachine {
private FoodType candy;
private FoodType chips;
private FoodType sodas;
private FoodType cookies;
private static String errorMessage = "A really bad error occurred.";
public VendingMachine(){
this.setupMachine();
}
private void setUpMachine(){
this.candy = new FoodType();
this.chips = new FoodType();
this.sodas = new FoodType();
this.cookies = new FoodType();
}
private boolean checkInput(){
if (this.candy==null || this.chips==null || this.sodas==null || this.cookies==null)
return false;
else
return true;
}
public void doSomething() throws Exception() {
if (!this.checkInput()) throw new Exception(VendingMachine.errorMessage);
// do things
}
}
这个类可以被称为
VendingMachine vendingMachine = new VendingMachine();
try {
//vendingMachine.checkInput() is not available because it is private
vendingMachine.doSomething(); // public method is available
} catch (Exception e){
// validation failed and threw an Exception
}
关于java - 将对象从一个私有(private)方法传递到另一个私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993946/