Skip to content
Advertisement

Avoid static method creating instances with same value

My program should not be able to create new instances with values of same name but I don’t know how to do. I imagined to put some if statments in the code but don’t know how to implement it

public class Smurf {

    private String name;

    public static Smurf createSmurf(String name) {
        System.out.println("Creating " + name + " Smurf");
        return new Smurf(name);
    }

    private Smurf(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println("My name is " + name + " Smurf.");
    }

    public void eat() {
        System.out.println(name + " Smurf is eating Smurfberries.");
    }

}

Advertisement

Answer

Not going to do your homework for you, but some guidance:

  • yes, when one Smurf instance has a name, then you need a non-static field in your class for that name
  • but then: when you want to ensure that names are unique, then you need to somehow keep track of all known / used names

A very simple (error-prone, not real-world ready) solution: you could have a private static final List<String> usedNames = new ArrayList<>() within that class.

That list is static, so all instances of your class see the same list.

Now you could check in your creation method wether the name provided as argument is already in that list. If so, refuse to create the new Smurf. Otherwise, create the new Smurf, and add the new name to that list.

And in case you wonder “and why doesn’t that work in the real world”: because A) it is a bad design that the Smurf class keeps track of all Smurf names and B) maybe Gargamel eats Careless Smurf at some point. Then you would need additional code to delete that name from the list. Or, you couldn’t use the name again when Careless Smurf wants to re-spawn. And so on.

Note: no smurfs were hurt during the writing of this answer though.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement