在Java中,静态方法中不能使用哪些词?

在Java中,静态方法中不能使用哪些词?,java,static,Java,Static,我知道我们不能在静态方法中使用“this”,因为它用于指向对象,静态方法由类而不是对象调用 在静态方法中是否还有其他不能使用的内容?在静态方法中不能引用类的非静态实例变量。如果没有实例,则不能使用实例成员。。。但这基本上就是你已经提到的 静态方法只能访问静态数据。 它无法访问/调用 类的实例(非静态)变量 它内部的其他非静态方法 无论如何都不能在中引用“this”或“super”关键字 示例:无法访问非静态数据,即实例变量“name”,也无法从静态方法内部调用非静态方法play()。 pub

我知道我们不能在静态方法中使用“this”,因为它用于指向对象,静态方法由类而不是对象调用


在静态方法中是否还有其他不能使用的内容?

在静态方法中不能引用类的非静态实例变量。

如果没有实例,则不能使用实例成员。。。但这基本上就是你已经提到的

静态方法只能访问静态数据。
它无法访问/调用

  • 类的实例(非静态)变量
  • 它内部的其他非静态方法
  • 无论如何都不能在中引用
    “this”
    “super”
    关键字
示例:无法访问非静态数据,即实例变量“name”,也无法从静态方法内部调用非静态方法play()。

public class Employee  {
          private String name;
          private String address;
          public static int counter;
      public Employee(String name, String address)   {
                this.name = name;
                this.address = address;
                this.number = ++counter;
               }

      public static int getCounter()  {
            System.out.println(“Inside getCounter”);
            name = “Rich”; //does not compile!

            // Let's say, e is a object of type Employee.
            e.play();      //Cannot call non-static methods. Hence, won't compile !
            return counter;
        }

     public void play() {
            System.out.println("Play called from Static method ? No, that's not possible");
     }
}

正如其他人所说,您只能访问静态变量和方法。还有一件事我想你应该注意的是,这也适用于像内部类这样的事情(这可能不是很明显,至少在我第一次尝试这样做时它就抓住了我):

给出编译时错误:

无法访问OuterClass类型的封闭实例。必须使用OuterClass类型的封闭实例限定分配(例如,x.new A(),其中x是OuterClass的实例)

但这是有效的:

public class OuterClass
{
    private static class InnerClass {}

    private static void staticMethod()
    {
        // Compiles fine
        InnerClass inner = new InnerClass();
    }
}

您也不能引用任何泛型类型,因为您没有具体(类型化)实例的上下文。

您不应该考虑“什么语法”在静态方法中无效。您应该将其视为“什么语义”在静态方法中无效。实例方法中的有效语法将是静态方法中的有效语法(有几个例外),但是在静态方法中有许多事情是不能做的,这些事情不是由方法中的语法引起的,而是由它所表示的语义引起的。
public class OuterClass
{
    private static class InnerClass {}

    private static void staticMethod()
    {
        // Compiles fine
        InnerClass inner = new InnerClass();
    }
}