user3637171
user3637171

Reputation: 1

Constructor - not creating any object if wrong validation

My task is : "In the SecuredNotepad constructor if the password doesn't contain any numbers, do not create SecuredNotepad object!"

public class SimpleNotepad {
private Page[] pages;

public SimpleNotepad(final int numberOfPages) {
    pages = new Page[numberOfPages];
    for (int i = 0; i < pages.length; i++) {
        pages[i] = new Page(String.valueOf(i + 1));
    }
}
}

public class SecuredNotepad extends SimpleNotepad {
private String pass;

public SecuredNotepad(int numberOfPages, String pass) {
    super(numberOfPages);
    if (pass.matches(".*\\d+.*") 
    {
        this.pass = pass;
    }
    else 
    {
        System.out.println("Password must contain at least one number!");
    }

}
}

In the constructor of SecuredNotepad I must call the superconstructor since SecuredNotepad extends SimpleNotepad. However, in constructor of SecuredNotepad I have validation for the parameter String pass (must contain at least one letter). If the parameter String pass does not pass the validation( I mean does not contain any letters), is there any possible way that the constructor will NOT create any object at all? If not, is there any way that the created object will be instance of class SimpleNotepad but not instance of SecuredNotepad?

Upvotes: 0

Views: 81

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

To prevent the constructor from constructing, you simply need to throw an exception from the constructor:

public SecuredNotepad(int numberOfPages, String pass) {
    super(numberOfPages);
    if (pass.matches(".*\\d+.*")) {
        this.pass = pass;
    }
    else {
        throw new IllegalArgumentException("Password must contain at least one number!");
    }
}

More about exceptions in the exceptions tutorial.

Upvotes: 5

Related Questions