Java Constructor issue – boolean condition

Tags:



I’m trying to put boolean condition in Constructor.

The task is to create Object only if the condition is true.

In the example below: if checkInitialPass() returns false, the Object should not be created.

SecuredNotepad(int numPages) {
        super(numPages);
        checkInitialPass();
}

Answer

That’s not possible.

You have (at least) two options:

1. Throw an exception

SecuredNotepad(int numPages) {
    super(numPages);
    if (!checkInitialPass()) {
        throw new IllegalArgumentException("Invalid");
    }
}

2. Create a static factory method

Make the constructor private and create a static factory method.

private SecuredNotepad(int numPages) {
    super(numPages);
}

public static SecuredNotepad createInstance(int numPages) {
    if (checkInitialPass()) {
        return new SecuredNotepad(numPages);
    }
    else {
        return null;
        // Or throw exception
    }
}

I would go for the factory method which would throw an exception if the initial pass failed. Alternatively, if you want to expand it even more, you could use a SecureNotepadFactory, as Thomas Timbul mentioned in the comments.



Source: stackoverflow