Recently I have got a compilation error in the code below:
import org.eclipse.swt.widgets.TreeItem;
Object parent; // can only be a Tree or a TreeItem
...
TreeItem item = new TreeItem((parent instanceof TreeItem) ? (TreeItem) parent : (Tree) parent, SWT.NONE);
Compiler says: “The constructor TreeItem(Widget, int) is undefined”
Then I have tried it with another code:
Object x = new Integer(1);
Test t = new Test((x instanceof String) ? (String) x : (Integer) x);
class Test{
public Test(String s){}
public Test(Integer i){}
}
And got another error: “The constructor Test(Object&Serializable&Comparable) is undefined”
So I was forced to use the traditional if-else structure. Any ideas why the compiler behaves so?
JLS §15.25 describes the ternary operator.
Basically, you can think of the ternary operator as a method: it can only have one “return type”. Since
StringandIntegerare two different objects, it finds the common superclass and all interfaces implemented by both and creates a return type from that. (StringandIntegerboth implementSerializableandComparableand extendObject, so you getObject & Serializable & Comparable.)