Class (static) methods

18 January 2012 By Nithya Vasudevan 284 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • If you have a requirement where the method’s behavior is independent of the state of the object then you go for static method.
  • Static methods have several restrictions:

    They can only invoke other static methods.

  • Static methods can only access other static methods
  • package com.ibytecode.keywords.staticdemo;
    public class Student {
    	static int count; //Initialized to zero
    	public static int count() { return count;}
    	public static int getCount()
    	{
    		reading("Java");//ERROR
    		return count(); //OK. 
    	}
    	public void reading(String book){ }
    }
    

    Compiler error:
    Cannot make a static reference to the non-static method reading(String) from the type Student

    They can only access static data/variable.

  • Static method can only use static data/variable and not instance variable
  • package com.ibytecode.keywords.staticdemo;
    public class Student {
    	int id;
    	static int count; 
    	public static int getCount()
    	{
    		++id;//ERROR
    		return count; //OK. 
    	}
    }
    

    They cannot use this or super in any way.

  • If you try to access super class static variable inside subclass’s static method using super keyword it results in a compiler error.
  • If you try to use this keyword inside a static method it results in a compiler error.