Khemchand Sachdeva
Khemchand Sachdeva

Reputation: 21

Calling a overloaded constructor with null argument

The no argument constructor will throw an error because the compiler doesn't know which constructor to call. What is the solution?

private Test() throws Exception {
    this(null);//THIS WILL THROW ERROR, I WAN'T TO CALL A SPECIFIC CONSTRUCTOR FROM THE TWO BELOW. HOW TO DO??
}
private Test(InputStream stream) throws Exception {

}



private Test(String fileName) throws Exception {

}

Upvotes: 2

Views: 535

Answers (2)

duffymo
duffymo

Reputation: 308763

I don't understand why all those constructors, so lovingly crafted, are private.

I'd do it this way:

private Test() throws Exception {
    this(new PrintStream(System.in);
}

private Test(InputStream stream) throws Exception {
    if (stream == null) {
        throw new IllegalArgumentException("input stream cannot be null");
    }   
    // other stuff here.
}    

private Test(String fileName) throws Exception {
    this(new FileInputStream(fileName));
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Typecast the null:

private Test() throws Exception {
    this((String)null); // Or of course, this((InputStream)null);
}

But it seems a bit odd that you'd want to call Test(String) or Test(InputStream) with a null argument...

Upvotes: 5

Related Questions