Engineers who have knowledge of Core Java concepts, must be familiar with static & non-static method in Java. However, most of them only know that static method can be called with class-name itself and non-static method with object of the class.
The very first point, we need to remember about Java that Instance variables of class like a & b in below class declaration, gets the memory space within the object of the class.
Therefor while designing a class, when we see that some methods are not working on the instance variable of a class, therefore it doesn’t make sense to invoke such method with object of the class. Like staticSumMethod() in below class:
class StaticMethodDemo{
int a,b; //Instance Variables
int nonStaticSumMethod()
{
a=10;
b=20;
return a+b;
}
static int staticSumMethod(int x,int y)
{
return x+y;
}
}
We can call the static & non-static method by object of the class like in below code. However, calling a static method with object of the class is not a good practice, as the memory occupied by instance variables [like a & b in above code] leads to wastage of memory.
StaticMethodDemo obj = new StaticMethodDemo( );
Obj. nonStaticSumMethod( ); //No Error & valid call
Obj.staticSumMethod(); //No Error, But not a good practice
In order to follow a good practice, Java recommends calling the static method with class-name itself. Like
StaticMethodDemo.staticSumMethod( )
I hope this would be helpful in your journey with Java.