3 Replies Latest reply: May 15, 2013 5:44 AM by EJP RSS

    Clarification on static keyword

    967983
      I read somewhere(don't know where) that static variable can only be used by a static method. But in the sample code below even a non-static function is able to use the static variable.
      public class Counter {
           static int count=0;
      
           void func1()
           {
                count++;
                System.out.println(count);
           }
           
           public static void main(String[] args) {
                Counter c=new Counter();
                c.func1();
           }
      
      }
        • 1. Re: Clarification on static keyword
          gimbal2
          Its the other way around, you can't use non-static stuff in a static method.
          • 2. Re: Clarification on static keyword
            baftos
            964980 wrote:
            I read somewhere(don't know where) that static variable can only be used by a static method. But in the sample code below even a non-static function is able to use the static variable.
            You read somewhere (don't know where) that non-static member variable can only be used by a non-static method. A static member variable belongs to the class, i.e. all objects of the class.
            A non-static member variable belongs to a specific object of a class and therefore cannot be used in a static method, which, by definition, is not associated with any object in particular.

            Edited by: baftos on May 15, 2013 5:27 AM
            • 3. Re: Clarification on static keyword
              EJP
              I read somewhere(don't know where) that static variable can only be used by a static method.
              No you didn't. You misunderstood, or you made it up, or you got it back to front. You've proven that this imaginary statement is incorrect. Not a real question.