0

So this code was given in an exam and the question was what's wrong with it. It's meant to create new objects of type SomeClass but only if they were not created earlier.

class Foo {
    private SomeClass x = null;
    public synchronized SomeClass getX() {
        if (x == null)
            x = new SomeClass();
        return x;
    }
}

My guess is that x and getX should be declared static since otherwise there may be multiple copies of x. Is that correct? if so is that the only problem in the code?

3
  • 3
    There's nothing inherently wrong with this class (except the missing closing brace, the bad naming and lack of documentation). It could not do what it's supposed to do, but since it has zero documentation, we can't know what it's supposed to do. Commented Apr 7, 2013 at 14:44
  • 2
    One closing brace (}) is missing. Commented Apr 7, 2013 at 14:45
  • 2
    Yes it should be static if you only want one instance. Commented Apr 7, 2013 at 14:47

1 Answer 1

1

You are trying to build a singleton factory method:

public class Foo {
    private static SomeClass x = null;
    public static synchronized SomeClass getSomeClass() {
        if (x == null)
            x = new SomeClass();
        return x;
    }
}

Note that if you really need this, you should also make SomeClass an inner class of Foo, and make the constructor of SomeClass private.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.