Bhavuk Mathur Bhavuk Mathur - 3 months ago 7
Java Question

Difference between Calling Static function from Object and Class itself

I was learning singleton design pattern and I did understand the concept. However, I have a doubt in the following code : -

class Token
{
private static int i = 5;
private static Token obj = new Token();

//Private Constructor
private Token()
{
}

//Returning the singleton object
public static Token getObject()
{
return obj;
}

public static int getValue()
{
return i;
}
}

public class TestMain
{
public static void main(String args[])
{
Token obj = Token.getObject();

System.out.println("Without object " + Token.getValue());
System.out.println("With object " + obj.getValue());
}
}


The instance variable i gets printed in both the cases -

Without object 5
With object 5


What is the difference between the two ways of getting instance variable and which one is recommended?

Answer

i is a static variable that belongs to class Token so it'll have the same value for all objects that are of type Token.

For all practical purposes, Token.getValue() is the same as obj.getValue() and you could use either, but for better readability, use Token.getValue() as it reinforces the idea that the static variable i and static method getValue() belong to the class as a whole and not to certain objects of that class.

Comments