Static methods in Java

Why static methods?

Take two people (two objects below).


The getName method will return the name of the first person, and the second person, but there’s something different about calculateAge in that it takes the date of birth of each person and compares it to the current date the find the age. Instead of every object working with a separate method, we can make the calculateAge method STATIC so that it’s shared between objects.

Snap 2014-04-22 at 16.18.44
Credit: Slide is a screen shot from Vivs slider nerd videos on youtube

In the above image, we can think of a “Common Area” where static variables and methods live. You don’t need an object to access a static method (just like with static variables)!

Snap 2014-04-22 at 16.24.20

In the above, we can consider the yellow box to be the world of objects, whereas the grey area, the area of static variables and methods, doesn’t require objects. However, if a static method REQUIRES use of a non static method, an object MUST BE CALLED to access that method. So in the above image, if the staticMethod() required the normalMethod() or the normal variable (int normal), it will require the object t1.

Leave a Reply