I know this is a silly question, but I'm wondering. I'm overriding the FilterWriter class in order to create a FixedWidthWriter class that will accept objects and convert them to flat-file format. Every new write() method accepts the object and the field width; the methods truncate or fill with spaces as necessary.
However, I realized that if a programmer (yes, I accidentally did this) calls the write(int) method instead of write(int,int), the program will cheerfully write the integer as a character, instead of converting the integer to its string value and correcting it to the proper field width.
I could, of course, override the write(int) method and throw a custom exception, but that seems a silly way to do it. Is there an easy way to override the method by making it invalid, so that the compiler will point out any call to write(int) as having the incorrect arguments?
If you declared a method with final modifier, any subclass can't override that method.
Joined: Mar 25, 2007
Thanks, but I don't have access to the superclass. I only have access to the class that is doing the inheriting. Is there a way from the inheriting class, the subclass, to prevent it from inheriting one of its superclass' methods?
You don't have to throw a custom exception. There's already an UnsupportedOperationException you can use. See the Javadoc for Iterator.remove() for an example of its use.
Alternatively, you override the single parameter method and call the two parameter method with a default value for the second paarmeter. As long as you document that this is what will happen and what the default value is, there should be no problem.
Liskov Substitution Principle suggests that a subtype should be able to be substituted for a supertype without clients noticing. That's clearly not what you want. Your class is a subclass because it's easy to reuse functionality from another class if you write a subclass of it.
However, ease and simplicity are not the same thing.
A simpler way would be to make a class whose instances hold an instance of what used to be the superclass, and then you can control what methods you expose. The fact that you'll be writing some methods that just delegate through to the wrapped object is an annoying side-effect, but not one that shows a problem with the mechanism; more with the language. This is called composition. Joshua Bloch says to favour composition over inheritance. I'd say to favour anything over implementation inheritance.
With programmatic access to methods such as that offered by AOP, or more flexible languages than Java, such as Lisp, Smalltalk, Ruby, Python, but not C++, you could implement all the delegate methods automatically.