class Languages{public static void main(String[] args){display();}
static void display(){System.out.println("Java is my favorite programming language.");}}
One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.
NOTE:Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:
new MockUp<ClassName>() {@Mockpublic int doSomething(Input input1, Input input2){return returnValue;}};
public static int min(int a, int b) {return (a <= b) ? a : b;}
The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
public class Demo{public static void main(String... args){Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:Displ(); //By method name itselfDemo.Displ(); //By using class name//Recommendedd.Displ(); //By using instance //Not recommended}
public static void Displ(){System.out.println("This static method needs to be called explicitly");}}