MrRockis
MrRockis

Reputation: 17

Java static instance VS get-method

I've been thinking about the difference between these code snippets. I understand that you can not set instance field if you are using getInstance (Second option below), but is there other differences?

public class MainClass {
    public static MainClass instance;

    public static void main(String[] args) {
        instance = new MainClass();
    }

    public void HelloWorld() {
        System.out.println("This is a test!");
    }
}

VS

public class MainClass {
    private static MainClass instance;

    public static void main(String[] args) {
        instance = new MainClass();
    }

    public MainClass getInstance() {
        return instance;
    }

    public void HelloWorld() {
        System.out.println("This is a test!");
    }
}

What is the difference between using "MainClass.instance.HelloWorld();" (First) or "MainClass.getInstance().HelloWorld();" (Second)

TLDR: Which one, and why? What is the difference?

Thanks! :)

Upvotes: 1

Views: 60

Answers (3)

Jags
Jags

Reputation: 837

Public

Current code is vulnerable by outsider who can change your instance with new one or even their own by subclassing. If you do not have need to change instance after first init then make it final and then public is good.

private

Saves you from above problem. Gives you more control to change instance if needed.

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

In the first example, you have declared instance as public making it vulnerable to accidental changes and therefore it is not recommended.

In the second example, you have declared instance as private making it invisible outside the class and thus ensuring that if required, it can be changed only through a public mutator/setter where you can put the desired logic how you want it to be changed.

Upvotes: 1

Scalability

The difference is somewhere down the line if your program has many calls to the instance, and you want to change where the instance comes from or perform an additional action while retrieving the instance, you can modify the getInstance() method, instead of adding code in every location where you used instance.

Upvotes: 0

Related Questions