FarShaD FarShaD - 4 months ago 11
Java Question

Check conditions in subclass before calling superclass constructor method

As we know in the constructor body of a subclass, the parent constructor must be the first statement otherwise we get a compile time error, This topic is already discussed here.

Let's assume that calling the parent constructor causes a heavy cost of system resources, In other hand in the subclass constructor we need to check some conditions first, if the conditions are satisfied we're good to go through the parent constructor else there's no need to go further (let's say throw an exception):

class parent {
parent(Object blah) {
//Heavy resource consuming tasks
}
}

class child extends parent {
child(Object blah, boolean condition) {
if (!condition) throw new IllegalArgumentException("Condition not satisfied");
super(blah); //Compile error!
}
}


If someone had the same issue I'm curious is there anyway to handle this situation or I must call the parent constructor first no matter how much resources it wastes and then throw the exception?

Answer

You could do something like this:

public class Jlaj extends ArrayList<String> {

    public Jlaj(int capacity) {
        super(checkCapacity(capacity));
    }

    private static int checkCapacity(int capacity) {
        if (capacity > 1000)
            throw new IllegalArgumentException();
        return capacity;
    }

    public static void main(String[] args) {
        new Jlaj(1001); // this throws IAE all right
    }
}

Note that you can only call static methods in this fashion, and that's good: calling instance methods on a partially initialized object is already a huge trouble, calling them even before superclass constructors would be a nightmare.