为什么static final int MAX_VALUE = 100;给出编译时错误

时间:2013-07-29 10:55:12

标签: java

        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的非法修饰符;只允许最终”

10 个答案:

答案 0 :(得分:4)

您无法在方法内声明静态变量。 静态变量属于该类;在方法内声明的变量是局部变量,属于该方法。

答案 1 :(得分:1)

局部变量不能是静态的。您可以创建最终的局部变量,也可以创建最终的静态类变量(实际上是常量,顺便说一句。),但不能创建本地静态变量:

public class A{
    static final int CLASS_CONST = 42;

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

       ...
    }
 }

答案 2 :(得分:1)

静态变量属于类。不是方法

method内声明的变量为local variables,属于method

所以它变成

final int MAX_VALUE = 100;

喜欢阅读:Docs on Understanding Instance and Class Members

答案 3 :(得分: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);
   }
}

答案 4 :(得分:0)

你不能在方法中删除static内容。把它向上移动一线。

答案 5 :(得分:0)

你不能在方法中创建静态final,你必须在方法之外创建它:

public class A {
          static final int MAX_VALUE = 100;

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

答案 6 :(得分: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");
    }
}

答案 7 :(得分: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");
      }
    }

答案 8 :(得分:0)

静态变量是类级变量,不能在方法中声明它们 根据{{​​3}}

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

答案 9 :(得分:0)

其他人已经指出静态成员属于类而不是特定实例。因此,您不必创建一个类实例来使用静态成员,而是可以直接调用SomeClass.SOME_STATIC_MEMBER。

如果不实例化该类,则不能调用非静态类的任何其他成员。意思是你有 -

public class SomeClass {

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

}

为了使用上面的SomeClass的 add 方法,你必须首先实例化 -

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

因此,没有必要允许我们在非静态方法中声明静态成员,因为我们使用该方法,我们必须实现该方法所属的类。