when to decide use static functions. when my function only called inside the same class is there is any need to make it static ?
as search I cant find full clear declaration
when to decide use static functions. when my function only called inside the same class is there is any need to make it static ?
as search I cant find full clear declaration
Static methods or variables are not part of just one Object, They are part of all instances of same type as declaring class.
When you declare a function as static in a class, for example we have class Animal
and this class will have a function that can be called without creating an Object out of this class. Let's say that the function is called roar()
If we declare it this way:
public void roar() {...}
To use it we would have to do the following steps:
Animal.roar() // It won't work!!!❌
Animal a = new Animal();
a.roar(); // Works ✔
If we declare it with the static
keyword:
public static void roar() {...}
Then we are able to do this:
Animal.roar(); // We call the function directly from the class, without creating an Object
Regarding your last question, you do not need to make a function static
to call it from within a class. You can but you don't need to.
If your function is being called only inside, there is no need to declare it static, you could even declare it as private to abstract the user from the inner implementation.
Let me break down static functions, I also had a hard time understanding at the beginning. For example, we have a
public static void main(String[] args) {}
It basically tells the JVM (Java Virtual Machine) that it can and should invoke this method on the start up of the program. However, it is declared as static so that JVM can call this method without instantiating the main class.
So think of static methods as something that is not bound to a specific object, it can be also variable (maybe even a constant) that is shared among the instances of that class.
I usually declare static methods for utility purposes.
Note: static variables and functions can be invoked in non static methods, however, the other way it will not work.
Hope I helped you :)