Up to this point, I have used the following code to restrict the application of some methods to instances of certain classes. For instance, using ItemListener, but this could be applied to many things,
public class mListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (!(e.getItemSelectable instanceof JCheckBox)) { //again, JCheckBox was chosen arbirtarily
System.err.println("mListener can only be applied to a JCheckBox");
return;
}
}
}
However, in a few places on the Oracle Java tutorials, I have seen the following code
public class mListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JCheckBox box = null;
try {
box = (JCheckBox) e.getItemSelectable();
} catch (ClassCastException ex) {
System.err.println("mListener can only be applied to a JCheckBox");
return;
}
}
}
Which is the best way to lock out classes that you don’t want a method applied to? This is especially the case with implementing interfaces, where the parameter can’t be changed.
In both cases, this is a programming error. The listener is being added inappropriately. The correct response for this is almost certainly not just printing out a message where it will probably never be seen – it’s an exception.
Simply casting will give you that exception without any work on your part, so just cast unconditionally, and don’t try to cover up programming errors.