So my coder friend hates using the static
coding. Yet my Java program is full of it to link between classes, and I have a lot of them!
Is it worth rewriting the whole code to remove the static method?
Is there any advantage of using one over the other?
Instance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object.
1) Java static variable The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.
Any method of a class which is not static is called non-static method or an instance method. To access a non-static method, we need an object instance to access it.
Static methods can be called without the object of the class. Instance methods require an object of the class. Static methods are associated with the class. Instance methods are associated with the objects.
1. An instance variable is one per Object, every object has its own copy of instance variable.
Eg:
public class Test{ int x = 5; } Test t1 = new Test(); Test t2 = new Test();
Both t1
and t2
will have its own copy of x
.
2. A static variable is one per Class, every object of that class shares the same Static variable.
Eg:
public class Test{ public static int x = 5; } Test t1 = new Test(); Test t2 = new Test();
Both t1
and t2
will have the exactly one x to share between them.
3. A static variable is initialized when the JVM loads the class.
4. A static method
cannot access Non-static
variable or method.
5. Static methods
along with Static variables
can mimic a Singleton Pattern
, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.
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