- 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 can only access other static methods
Static methods have several restrictions:
They can only invoke 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.
package com.ibytecode.keywords.staticdemo; public class Student { int id; static int count; public static int getCount() { ++id;//ERROR return count; //OK. } }