Skip to main content

Is it safe to return a new object from static method? [Resolved]

Is it OK to have a class something like this

public class Weapon {
    private string name;
    private int might;
    // etc...

    private Weapon(String name, int might) {
        this.name = name;
        this.might = might;
    }

    public static final Weapon Alondite = new Weapon("Alondite", 16);
    // 100++ weapon
}

Then calling the weapon anywhere in the project, like this Weapon.Alondite, will this create new object every time the static method member called?

Or should I do like this, to ensure the object only created once

public class Weapon {
    private string name;
    private int might;
    // etc...

    private Weapon(String name, int might) {
        this.name = name;
        this.might = might;
    }

    private static Weapon mAlondite;
    public static Weapon Alondite() {
        //if (mAlondite == null) {
        //    mAlondite = new Weapon("Alondite", 16);
        //    return mAlondite;
        //} else {
        //    return mAlondite;
        //}

        // EDIT: as suggested by everyone
        if (mAlondite == null) {
            mAlondite = new Weapon("Alondite", 16);
        }
        return mAlondite;
    }
}

Question Credit: SIRS
Question Reference
Asked January 22, 2018
Posted Under: Programming
25 views
3 Answers

Your Answer
D:\Adnan\Candoerz\CandoProject\vQA