@Whoa314 said:
@Gazzonyx said:Strangely proud and embarrassed by this line of code from a test GUI I'm using. I like to cast at the minute.
It's ugly but functional. I should mention that PersonPanels extend ContactPanels. Still, ...
how does the casting into (PersonPanel) possibly change the behavior of that line?
It doesn't change what method gets called. But in Java, casts throw an exception if the object isn't an instance of the right type. So it will throw an exception if contactPanel is not an instance of PersonPanel. The OP said that this is test code, and in test code you often want to check objects are the right type. I'm not sure if that's what the OP is trying to do, or if the OP has just misunderstood Java. (The comment suggests the latter).
Note that in Java (and C), the result of the ?: operator has a type. It's not a different type depending on which branch got evaluated, it has to be the same type for both branches. The compiler will choose ContactPanel for this type, since PersonPanel can be converted to ContactPanel. So the compiler's going to expand that line of code as:
public void showContact(Contact contact)
{
/* eat your heart out, polymorphism! */
((contact instanceof Person) ? (ContactPanel)(PersonPanel)contactPanel : contactPanel).setContact(contact);
}
Here's how I'd write the function, keeping the behaviour exactly the same:
public void showContact(Contact contact)
{
if ((contact instanceof Person) && !(contactPanel instanceof PersonPanel))
/* TODO: Document why we throw ClassCastException here... */
throw ClassCastException();
contactPanel.setContact(contact);
}