You can do this
Class cl = flag ? new Class(100) : new Class();
By definition, the type of a ? :
is the same as the last argument. i.e. Object, you cannot make it type less and value less.
Question
Just for curiousity...
Assume I have a Class with two constructors:
public Class(){}
public Class(int x){}
and I want to create a new class through with the following statement below:
new Class( ( true ) ? 100 : null);
Would this be acceptable? Will null instantiate the Class with the empty/default constructor? If not, is there a way to accomplish this with the ternary operator?
Note that I am on Java version 6.
Solution
You can do this
Class cl = flag ? new Class(100) : new Class();
By definition, the type of a ? :
is the same as the last argument. i.e. Object, you cannot make it type less and value less.
OTHER TIPS
new Class( ( true ) ? 100 : null);
the reason you wont have an empty constructor is because, the only choices we would get would be new Class(100)
and new Class(null)
1. new Class(null)
2. new Class()
Now 1 is not same as 2
null is comprehended as an Object
, where as the constructor is expecting a int
. If we had
public Class(Integer x){}
then new Class(null)
would have been allowed since Object is a super class for Integer. Thus the only alternative is
boolean check = true;
check ? new Class(100) : new Class();
You can use variable arguments
Class(int... x){} //constructor
and then use new Class();
or new Class(2);