i would like to ask the question when it would be advantageous to use static variables/methods or in the other case instance variables/methods in Java?
I know that it depends on the certain case (like programming util-classes as static methods), but can we declare something like a general strategy?
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.
Static variables belong to the class, with all objects of a class sharing a single static variable. Static methods are associated with the class, not objects of the class. Static variables are used with the class name and the dot operator, since they are associated with a class, not objects of a class.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
At novice level :
Use instance variables when : Every variable has a different value for different object. E.g. name of student, roll number etc..
use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students.
Static variable: When you need something that will be used through out the application and every instance need to know the variable.
Instance variable: It will be different from object to object and object's property while static variable is Class's property.
Static function: Used to do some utility task. Can be called without any object declaration.
Instance function: Need object to call this function.
static or instance depends on your uses .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With