2017-06-02 67 views
-3

因爲我是新的java。我已經搜索了有關在Java中的靜態平均值,我得到了堆棧溢出的解決方案here但是當我編譯它顯示錯誤。有人可以建議我錯在哪裏?<identifier>預計java編譯錯誤

public class Hello 
{ 
    // value/method 
    public static String staticValue; 
    public String nonStaticValue; 
} 

class A 
{ 
    Hello hello = new Hello(); 
    hello.staticValue = "abc"; 
    hello.nonStaticValue = "xyz"; 
} 

class B 
{ 
    Hello hello2 = new Hello(); // here staticValue = "abc" 
    hello2.staticValue; // will have value of "abc" 
    hello2.nonStaticValue; // will have value of null 
} 

enter image description here

+0

知道static'成員變量的'的使用,並且還非靜態成員變量 –

回答

3

以及在課堂上水平,你只能定義一個類,斜面的屬性做哪些你在ClassA和ClassB的做任何處理。處理只能在方法中完成。

只需添加主要方法使物體的

​​

主要方法是在Java中的任何程序的入口點。不要擔心,如果你對這個主要方法的調用感到困惑。

+1

的使用或將其在靜態代碼塊 –

+0

這doesn't編譯,可變訪問'hello2.staticValue;'不能只是獨立的(我知道你可能忘了從上面複製任務) – SomeJavaGuy

+0

我編輯它,它現在應該工作。您正在使用對象引用訪問靜態變量。只能使用類引用來訪問靜態變量。 –

1

首先,要運行Java文件,您需要一個包含主要方法的公共類。更改變量內容只能在一個方法中完成。

public class Hello(){ 
    public static String staticValue; 
    public String nonStaticValue; 
    public static void main(String[] args){ 
    Hello hello = new Hello(); 
    Hello.staticValue = "abc"; 
    hello.nonStaticValue = "xyz"; 
    Hello hello2 = new Hello(); 
    System.out.println(hello2.staticValue); 
    System.out.println(hello2.nonStaticValue); 
    } 
}