Prohibit the use of methods from superclasses

Posted by Steven

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:

  1. public class CustomDateField extends JTextField {
  3. public void setDate(Date date) {
  4. c.setTime(date);
  5. // the real method was a bit more complicated, but for the example that is sufficient
  6. super.setText(String.valueOf(c.get(Calendar.YEAR)));
  7. }
  9. /**
  10. * @deprecated Use setDate(Date date) instead
  11. */
  12. @Deprecated
  13. @Override
  14. public void setText(String arg0) {
  15. throw new RuntimeException(
  16. "This method is not supported. Use setDate(Date date) instead.");
  17. }
  18. }

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:

  1. public class CustomDateFieldTest {
  3. CustomDateField field;
  5. @Before
  6. public void before() {
  7. field = new CustomDateField();
  8. }
  10. @Test(expected = RuntimeException.class)
  11. public void setTextDoesntWorkAnymore() {
  12. field.setText("Text");
  13. }
  15. @Test
  16. public void setDateWorks() {
  17. Date date = new Date();
  18. field.setDate(date);
  19. assertEquals("field.getText()", "2013", field.getText());
  20. }
  21. }

Because I've never seen this combination of @Deprecated and throwing an exception before, I want to record it here.



This breaks existing code in a real mean way: It still compiles, but it doesn't work. If you are willing to break existing code in such a harsh fashion just remove the method completely.

How exactly does this break existing code? Because this class is new, there are no uses of it, hence no code gets broken. The only way I can think of is referencing the super class of the new class (JTextField) in a collection. This way, there is a collection of JTextField from which some will throw exceptions when setting a text - namely the new subclasses. That sounds bad ... did you mean that?