2011-05-18 31 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 
    } 
} 
相關問題