Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static variables/methods and when to use instance variables/methods in Java? [closed]

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?

like image 587
user3133542 Avatar asked Jan 16 '14 07:01

user3133542


People also ask

When would you use a static method over an instance method?

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.

When should we use static variables in Java?

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.

When we use static variables and methods?

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.

Why static method Cannot use instance variable?

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.


2 Answers

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.

like image 57
TheLostMind Avatar answered Sep 21 '22 10:09

TheLostMind


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 .

like image 26
Md. Yusuf Avatar answered Sep 19 '22 10:09

Md. Yusuf