2011-05-18 39 views
0

如果我举个例子一个项目。里面有两堂课。例如:X和Y.我让它们成为我想要的,并且我想在Y中创建一个主要方法。只有system.out.printlf中的X和Y中的值。但是它写道,如果我需要将它们设置为静态想要运行这个。我试图创建一个只有主类和X Y值的新文件,但它显示了一个错误。我错过了什么?如果我在一个项目中有更多的文件,我需要使所有字段都是静态的?

+2

请出示一些代码.. – hvgotcodes 2011-05-18 15:29:52

回答

0

主要方法声明为static

​​

里面的main,它只能访问存在于封闭类的静态变量。你会看到这个例如使用这段代码:

public class X { 
    private int i = 5; 

    public static void main(String[] args) { 
     System.out.println(i); 
    } 
} 

为了让你需要声明istatic以上工作:

public class X { 
    private static int i = 5; 

    public static void main(String[] args) { 
     System.out.println(i); 
    } 
} 

一个更好的方法是这样:

public class X { 
    private int i = 5; 

    public X() { 
     System.out.println(i); 
    } 

    public static void main(String[] args) { 
     new X();  
    } 
} 

静态方法只能访问声明为静态的静态方法和其他变量。

This文章也可能帮助你了解这里发生了什么。

2

您错过了对象创建。在Y文件中尝试X x = new X();。我建议阅读一些关于Java的教程,从here开始。

0

我猜这是因为一切都发生在主方法里面,这确实是静态的权利?例如

public class C { 
int X; 
int Y; //or whatever other type 
.. 
public static void main(String args[]) { 
    System.out.print(X); //this won't work! 
} 
} 

代替使用此aprroach:

public class C { 
int X; 
int Y; //or whatever other type 
.. 
public static void main(String args[]) { 
    C inst = new C(); 
    System.out.print(c.X); //this will work! 
} 
} 
0

的主要方法是静态的,可以只访问从类静态字段。 非静态领域属于一个实例/对象,你必须创建:

public class X { 
    static int a = 0; 
     int b = 0; 


    public static void main(String[] args) { 
    System.out.println(a); // OK -> accesses static field 
    System.out.println(b); // compile error -> accesses instance field 
    X x = new X(); 
    System.out.println(x.b); // OK -> accesses b on instance of X 
    } 
} 
相关问题