Wednesday, April 18, 2018

java - Difference between Static methods and Instance methods

In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.



This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.



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() as:



A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3


B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5

//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10

class B{

int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}


In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...