Java,在类中使用变量

时间:2010-11-10 10:15:18

标签: java variables global-variables

如何在另一个类中使用变量drawMax?

public int DrawNumberSetting (int drawMax)
{
    System.out.print ("Please enter the maximum number of draws you want to play: ");
    drawMax = scan.nextInt ();
    return drawMax;
}

2 个答案:

答案 0 :(得分:1)

让我们说你的drawNumberSetting(int drawMax)在类A中声明。这意味着任何其他具有类A实例的类都可以调用该方法并使用返回的值。

class B
{
    public void my otherMethod()
    {
        A a = new A();
        int drawMax = a.drawNumberSetting(5);
    }
}

答案 1 :(得分:0)

您可以将drawMax转换为类级变量并提供getter \ accessor方法,如下所示:

private int drawMax;

public void DrawNumberSetting ()
{
    System.out.print ("Please enter the maximum number of draws you want to play: ");
    drawMax = scan.nextInt ();
}

public int getDrawMax()
{
   return drawMax;
}