Day28 : Using Static Method
Using Static Method
In Java just like we can have static data similarly we also can have static method in our class and java recommends two situation when we should make our method static.
1) When we've a method in the class which is only accessing static data member of the class.
For Example : In the previous program the method showNextId() must be declared as static because it is only accessing static data nextId in its body. The most important benefit of doing this will be that now we can call the method showNextId() without using any object by simply using class name.
code:
public static void showNextId()
{
System.out.println("Next emp id will be " + nextId);
}
call :
Emp.showNextId();
2) Whenever we've a class without any instance variable then all the method of that class must be declared as static. For Example :
public class MyMath()
{
public static void main(String [ ] args)
{
int c;
c = a + b;
return c;
}
public static int max(int a, int b)
{
if(a>b)
{
return a;
}
}
Special Note:
Based on the Above rule the developers of java language themselves have declare some very commonly used classes, with every method as static and they are:
# Java.lang.Math // No Obect should be created
# Java.util.Arrays // No Obect should be created
# Java.util.Collection // No Obect should be created
Comments