Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Static vs Instance

Tags:

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?

like image 857
Kezz Avatar asked Aug 10 '12 18:08

Kezz


People also ask

Is an instance method static?

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.

When would you use a static instance?

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.

Are instance methods non static?

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.

How would you call a static method vs an instance method?

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 Answers

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.

like image 77
Kumar Vivek Mitra Avatar answered Oct 02 '22 01:10

Kumar Vivek Mitra