+ 2
When to make a method static and when not to?
I get confused when making a method static. I need a brief description.
2 ответов
+ 2
Hello Blue!!
A static method belongs to the class.
A non static method belongs to the instance of a class.
For example you have a class Person and a method which returns the name. Each person has a different name, so it would make not sense to make this method static.
But imagine another class Calculator which returns the result of some calculations. Do you really need an instance? Not really.
Here it could make sense to use static methods:
static int add(int a, int b){
return a + b;
}
in main:
int result = Calculator.add(4, 5);
Another example is the Math Class: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
All methods are static.
+ 1
I found a similar thread on stack overflow. Hope it helps👇
https://stackoverflow.com/questions/2713601/when-to-make-a-method-static#:~:text=Use%20static%20methods%20when%20you,method%20of%20a%20Math%20class.