samedi 13 août 2016

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?

Aucun commentaire:

Enregistrer un commentaire