2017-06-02 69 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); 
    } 
}