JDK-5047104 : tertiary operator drawback: an explicit cast is required.
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 1.4.2
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2004-05-13
  • Updated: 2004-05-13
  • Resolved: 2004-05-13
Related Reports
Duplicate :  
Description

Name: rmT116609			Date: 05/13/2004


FULL PRODUCT VERSION :
java version "1.4.2"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-b28)
Java HotSpot(TM) Client VM (build 1.4.2-b28, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [Version 5.1.2600]

A DESCRIPTION OF THE PROBLEM :
The tertiary operator has a drawback.
The problem is that it cannot identify that two objects b & c are from the same base class, without requiring an explicit cast

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Consider an abstract base class A
Two derived classes B & C
Also a method set(A object) which accepts an object of type A


B b = new B();
C c = new C();
boolean isValid = false;

set(isValid ? b : c); //this does not work

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
set(isValid ? b : c); should work without cast
ACTUAL -
set(isValid ? b : c); requires cast

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Incompatible types; found C required B

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public class Test {
    public static void main(String args[]) {
	B b = new B();
	C c = new C();
	boolean isValid = false;
	
	set(isValid ? b : c);
    }
    
    public static void set(A obj) {}
}

abstract class A {}

class B extends A{}

class C extends A{}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Cast either b or c to A as follows:

set(isValid ? (A) b : c);

OR

set(isValid ? b : (A) c);
(Incident Review ID: 242826) 
======================================================================