Bhavuk Mathur
Bhavuk Mathur

Reputation: 1078

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?

Upvotes: 0

Views: 156

Answers (3)

Usman Shahid Amin
Usman Shahid Amin

Reputation: 261

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, obj.getValue() is the same as Token.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.

Upvotes: 2

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27496

There is little difference, for instance access you need the actual instance, which you don't always have.

As for preference it depends on who you ask. For me static fields and methods should be accessed using the class not instance - this clearly shows that it is static.

Upvotes: 1

ByeBye
ByeBye

Reputation: 6956

In fact in obj you have reference to your singleton. So calling Token.getValue() reference to same obj as obj.getValue()

Upvotes: 1

Related Questions