2013-07-29 65 views
-1
 public class A{ 
      public static void main(String[] args){ 
      static final int MAX_VALUE = 100; //COMPILE TIME ERROR 
      System.out.println("MAX_VALUE"); 
      } 
     } 

爲什麼static final int MAX_VALUE=100;給出編譯時錯誤,它給出的錯誤爲「參數MAX_VALUE的非法修飾符;只允許最終」爲什麼static final int MAX_VALUE = 100;給編譯時錯誤

+2

'靜態'變量不能在裏面的方法。刪除修飾符'靜態'! – NINCOMPOOP

+1

在java中,我認爲靜態變量不能像C/C++ –

+0

+1這樣的方法來提醒OP有關 – NINCOMPOOP

回答

4

您不能在方法中聲明靜態變量。 靜態變量屬於該類;在方法中聲明的變量是局部變量,屬於該方法。

0

你不能在一個方法裏面用delcare static東西。將其上移一行。

1

局部變量不能是靜態的。您可以創建一個最終的局部變量,或最終的靜態類變量(實際上是常量,順便說一句。),但不是局部靜態變量:

public class A{ 
    static final int CLASS_CONST = 42; 

    public static void main(String[] args){ 
     final int LOCAL_CONST = 43; 

     ... 
    } 
} 
+0

+1對於實際編碼! – NINCOMPOOP

1

靜態變量屬於class.Not方法

method內聲明的變量爲local variables,屬於該method

,使其成爲

final int MAX_VALUE = 100; 

喜歡閱讀:

public class A { 
      static final int MAX_VALUE = 100; 

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

你不能在方法創建靜態最終,你必須在方法外創建應該在A類中聲明這個常數,而不是在main()方法中

public class A{ 

    static final int MAX_VALUE = 100; //COMPILE TIME ERROR 

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

關鍵字static不能在方法內部使用。這將是有效的代碼:

public class A{ 

    static final int MAX_VALUE = 100; // This line can't go in a method. 

    public static void main(String[] args){ 
     System.out.println("MAX_VALUE: "+MAX_VALUE); 
    } 
} 
0

變化

public class A{ 
     public static void main(String[] args){ 
     static final int MAX_VALUE = 100; //COMPILE TIME ERROR 
     System.out.println("MAX_VALUE"); 
     } 
    } 

public class A{ 
     static final int MAX_VALUE = 100; //NO ERROR YAY!! 

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

靜態變量是一流水平的變量,你不能在方法聲明它們。
根據Docs

 
Sometimes, you want to have variables that are common to all objects. 
This is accomplished with the static modifier. Fields that have the static 
modifier in their declaration are called static fields or class variables. 
They are associated with the class, rather than with any object 
0

其他已經指出,靜態成員屬於類,而不是一個具體的實例。所以你不必創建一個類實例來使用靜態成員,而是直接調用SomeClass.SOME_STATIC_MEMBER。

如果不實例化該類,則不能調用任何非靜態類的其他成員。這意味着如果你有─

public class SomeClass { 

    public int add (int x, int y){ 
     return x + y; 
    } 

} 

供您使用添加SomeClass的的上述方法,你必須實例一線

SomeClass someClass = new SomeClass(); 
int sum = someClass.add(5, 10); 

那麼,有沒有讓我們來聲明靜態成員的點在一個非靜態的方法中,我們要使用這種方法,我們必須安排那個方法所屬的類。

相關問題