访问静态变量

时间:2014-04-09 06:35:38

标签: java static

我有以下情况。有两个类 A类 B类。这两个类都具有以下性质。

A类

static public int a = 10;
static public int b = a-3;

B类

A.a = 5; 
// print b here.

b =?

如果我在某处出错,请纠正我。谢谢。

6 个答案:

答案 0 :(得分:1)

即使它是对象或原始也是不可能的,因为java支持传递值而不是传递参考

答案 1 :(得分:1)

你做不到。但是,您可以编写一个方法来为两个变量执行此操作:

private static void setValue(int value) {
    b = val;
    A.a = val;
}

如果你坚持这样做"直接",考虑转向C / C ++:)

答案 2 :(得分:1)

这可能与您想要的行为过于接近。

class IntWrapper {
    int inside;
    public IntWrapper(int i) {
        inside = i;
    }
}
class A {
    static IntWrapper a = new IntWrapper(10);
    static IntWrapper b = a;
}
public class B {
   public static void main(String[] args) {
       A.a.inside = 5;
       System.out.println(A.b.inside);
   }
}

答案 3 :(得分:0)

没有。即使static public Integer a = 10;(参考类型)也不会更改此值,因为您正在更改变量指向的对象。

你可以做的是设置getter和setter,一个la C#属性:

private static int a;
private static int b;
public static int GetA() {return a;}
public static int SetA(int newA) {a = newA; b = newA}
public static int GetB() {return b;}

如果您希望b只是基于a的计算,这非常简单:

private static int a;
public static int GetA() {return a;}
public static int SetA(int newA) {a = newA;}
public static int GetB() {return a - 3;}

如果你只想要一个语句来更新两者,你可以用

来完成
b = a = 3;

虽然不是那么令人兴奋。

答案 4 :(得分:0)

public class A {
    private static int a;
    private static int b;

    static {
        setAB(10);
    }

    public static int getA() {
        return a;
    }

    public static int getB() {
        return b;
    }

    public static void setAB(int value) {
        a = value;
        b = value;
    }
}

答案 5 :(得分:0)

如果b是...的函数,为什么不将它声明为静态函数:

class A {
    static IntWrapper a = 10;
    public static getB(){
       return a - 3;
    }
}

这样,当a更改时,它会正确更新 如果您不需要这种行为,将无法设置 b

相关问题