如何定义类外的全局变量?

时间:2013-11-28 02:14:45

标签: java

我想定义可以与类共享值的变量。

所以我尝试了以下。

但是发生了错误。

如何将值分享给类?

package com.company;

    /////// Error occurred ///////
    int sharedValue = 100;   // <- How to share to classes?
    //////////////////////////////

    public class Main {

        public static void main(String[] args) {
            sharedValue += 10;

            GlobalTest globalTest = new GlobalTest();
            globalTest.printGlobalValue();
        }
    }

    class GlobalTest {
        void printGlobalValue() {
            System.out.println(sharedValue);
        }
    } 

3 个答案:

答案 0 :(得分:2)

您可以在班级中将其声明为静态值:

public class Main {
    public static int sharedValue = 100;
    ....
}  

使用以下方法从其他类访问它:

Main.sharedValue

答案 1 :(得分:0)

在类中使用static

public class Blah {
    public static int a = 100;
}

可以通过Blah.a

访问

答案 2 :(得分:0)

您还可以添加公共getter方法来访问sharedValue,如下所示:

public class Main {

   private int sharedValue;
    public void setSharedVallue(int sv)
    {
        sharedValue=sv;
    }
    public int getSharedvalue()
    {
        return sharedValue;
    }
    // Other code.
}