In short, static methods and static variables are class levels, where, since instance methods and instance variables are instance or object level.
This means that whenever an instance or object is created (using the new ClassName ()), this object will save its own copy of instace variables. If you have five different objects of the same class, you will have five different copies of instance variables. But static variables and methods will be the same for all these five objects. If you need something in common for each created object, make it static. If you need a method that does not require processing of specific objects, make it static. The static method will only work with a static variable or will return data based on the arguments passed.
class A { int a; int b; public void setParameters(int a, int b){ this.a = a; this.b = b; } public int add(){ return this.a + this.b; } public static returnSum(int s1, int s2){ return (s1 + s2); } }
In the above example, when you call add () like:
A objA = new A(); objA.setParameters(1,2);
In the first class, add () will return the sum of the data passed by a specific object. But the static method can be used to get the sum from any class that is not independent, if any particular instance or object. Consequently, for general methods that require only arguments to work, you can make them static in order to keep everything DRY.
Prakash Jun 22 '17 at 4:27 2017-06-22 04:27
source share