如何在java中访问这个变量?

时间:2013-12-14 21:54:48

标签: java

我是Java的初学者,我来自C#。看看这段代码:

public class Ampel {
    public Ampel(boolean r, boolean y, boolean g) {
        boolean red = r,
                yellow = y,
                green = g;
    }
    public void GetStand() {
        System.out.println(red);
        System.out.println(yellow);
        System.out.println(green);
    }
}

我无法在GetStand()中访问“红色”或“黄色”和“绿色”。我该怎么办?

3 个答案:

答案 0 :(得分:3)

您目前正在构造函数中声明 local 变量。您需要声明实例变量。例如:

public class Ampel {
    private final boolean red;
    private final boolean yellow;
    private final boolean green;

    public Ampel(boolean r, boolean y, boolean g) {
        red = r;
        yellow = y;
        green = g;
    }

    // Name changed to follow Java casing conventions, but it's still odd to have
    // a "get" method which doesn't return anything...
    public void getStand() {
        System.out.println(red);
        System.out.println(yellow);
        System.out.println(green);
    }
}

请注意,等效的C#代码将以完全相同的方式工作。这个不是 Java和C#之间的区别。

答案 1 :(得分:0)

将布尔值定义为类属性而不是构造函数范围中的变量。

答案 2 :(得分:0)

将红色,黄色和绿色定义为实例变量。

public class Ampel {
    private boolean red, yellow, green;
    public Ampel(boolean r, boolean y, boolean g) {
        red = r;
        yellow = y;
        green = g;
   }

   public void getStand() { // java convention is to camelCase method names
       System.out.println(red);
       System.out.println(yellow);
       System.out.println(green);
   }
}
相关问题