You are here
Prohibit the use of methods from superclasses
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:
c.setTime(date); // the real method was a bit more complicated, but for the example that is sufficient } /** * @deprecated Use setDate(Date date) instead */ @Deprecated @Override "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(); } public void setTextDoesntWorkAnymore() { field.setText("Text"); } @Test public void setDateWorks() { 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.

Comments
Bad idea
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.
Re: bad idea
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?