开发者

in Java what words cant we use inside a static method?

I know we cant use "this" inside a static method, because this is used to point to an object and static methods are called by classes and not objects.

Is there something else you开发者_StackOverflow社区 cant use inside a static method?


you may not use instance members without an instance ... but that's basically what you already mentioned ...


you can't refer to a class's non-static instance variables inside a static method.


Static method can only access static data.
It cannot access/call

  • Instance(non-static) variables of the class.
  • Other non-static methods from inside it.
  • Cannot refer to "this" or "super" keywords in anyway

Example : Cannot access non-static data i.e instance variable "name" and cannot call non-static method play() from inside static method.

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");
     }
}


As others have said, you can only access static variables and methods. One more thing I guess you should watch out for is that this applies to things like inner classes too (this may not be immediately obvious, at least it caught me out the first time I tried to do this):

public class OuterClass
{
    private class InnerClass {}

    private static void staticMethod()
    {
        // Compile-time error!
        InnerClass inner = new InnerClass();
    }
}

Gives a compile-time error:

No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass).

But this is valid:

public class OuterClass
{
    private static class InnerClass {}

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


You also can't refer to any generic types, because you don't have the context of a concrete (typed) instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜