A couple of days ago, I saw an interesting way to prohibit the use of a method from a superclass. A coworker of mine wrote a subclass of a JTextField that should display a date in a specific fashion. Before you comment the obvious: Yes, there where reasons not to use JFormattedTextField. ;)
Here’s how he wrote the new class:
public class CustomDateField extends JTextField {
public void setDate(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
// the real method was a bit more complicated, but for the example that is sufficient
super.setText(String.valueOf(c.get(Calendar.YEAR)));
}
/**
* @deprecated Use setDate(Date date) instead
*/
@Deprecated
@Override
public void setText(String arg0) {
throw new RuntimeException(
"This method is not supported. Use setDate(Date date) instead.");
}
}
Because the new textfield should only work with java.util.Date, the common setText() is rendered unusable. Therefore, a new method is offered. The class works as follows:
public class CustomDateFieldTest {
CustomDateField field;
@Before
public void before() {
field = new CustomDateField();
}
@Test(expected = RuntimeException.class)
public void setTextDoesntWorkAnymore() {
field.setText("Text");
}
@Test
public void setDateWorks() {
Date date = new Date();
field.setDate(date);
assertEquals("field.getText()", "2013", field.getText());
}
}
Because I’ve never seen this combination of @Deprecated and throwing an exception before, I want to record it here.