【问题标题】:Error when declaring & initializing string as static in java [duplicate]在java中将字符串声明和初始化为静态时出错[重复]
【发布时间】:2016-06-23 06:19:16
【问题描述】:

我正在尝试将本地 String 变量声明和初始化为 static ,但出现编译错误,显示 Illegal modifier static。为什么会这样?

这是我的代码:

public class StringInstance {
    public static void main(String[] args) {
    static String s = "a";

    if(s instanceof String){
        System.out.println("Yes it is");
     }
  }
}

【问题讨论】:

  • static 仅适用于班级成员。您不能在方法中声明 static 变量。
  • @faizalvasaya 因为错误表明我们在方法中不能有静态字段。那没有意义。您需要删除静态修饰符。
  • static 表示类级别。您必须在类级别声明它们。

标签: java string exception


【解决方案1】:

您声明的字符串将是静态的,因为它的范围是静态的,因此您不需要 static 修饰符。但是如果你想在main() 的范围之外声明它是静态的,那么就这样做:

public class StringInstance {
  static String s = "a";
    public static void main(String[] args) {

    if(s instanceof String){
        System.out.println("Yes it is");
    }
  }
}

【讨论】:

  • 我的疑问是,由于 main 是一个静态块,应该可以在其中声明为静态块。
  • @faizalvasaya 它已经是静态的,没有显式的 static 修饰符,因为它在静态范围内。
  • 谢谢@Jonah Haney!你澄清了我的疑问。
猜你喜欢
  • 1970-01-01
  • 2011-07-12
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
相关资源
最近更新 更多