tags:

views:

86

answers:

1

I have a form class with a method:

IText getSearchField()

The IText interface is something implemented by a subclass of JTextField called MyTextField.

For reasons beyond my control, I cannot get the control from the form class typed as MyTextField, as JTextField, Component, or anything else in the MyTextField type hierarchy.

I am accessing the form class object from a driver object, and would like to have the driver set the focus onto the search field retrieved by the getSearchField() call.

I could use the requestFocusInWindow() method of the Component class to do this. However, first I would need to cast the result of the getSearchField() call to something in the MyTextField type hierarchy, since the call to getSearchField() returns an IText.

My question is, should I cast to MyTextField? to Component? to something in between?

Why? And which would be fastest?

+6  A: 

Cast to the least specific you need. That is, if A is a superclass of B and you only need methods from A, cast to A. If you also need methods from B, cast to B.

Which would be the fastest? Why do you ask this? It wouldn't make a difference.

Sjoerd
So does that mean casting always happens at the same speed, regardless of what type you cast to?
Tom Tresansky
Performance impact of any cast will be negligible.
Sjoerd
Well, casts are surprisingly expensive because the JVM has to verify at run time that the cast is indeed legal. But I would be quite surprised if there was a significant difference in run time depending on what you cast it to. That would be amusing to benchmark. In any case, maintainability is more important than a minor performance gain even if there is one.
Jay