Lots of answers, but I would add my own $ 0.02.
I rarely redefine classes, but under certain circumstances. At least 1 has already been mentioned when class frameworks are intended to be extended. Two further examples are provided:
1) If I want to customize the behavior of a particular class. Sometimes I want to change how a particular class works, or I want to know when some method is called, so I can call something. Often, specific classes define a hook method, the only use of which for subclasses overrides the method.
Example: we redefined MBeanExporter because we need to be able to unregister the JMX bean:
public class MBeanRegistrationSupport {
Our class:
public class UnregisterableMBeanExporter extends MBeanExporter { @Override protected void onUnregister(ObjectName name) {
Here is another good example. LinkedHashMap designed to override the removeEldestEntry method.
private static class LimitedLinkedHashMap<K, V> extends LinkedHashMap<K, V> { @Override protected boolean removeEldestEntry(Entry<K, V> eldest) { return size() > 1000; }
2) If a class shares a significant number of overlaps with a specific class, with the exception of some settings for functionality.
Example: My ORMLite project processes persistent fields of Long and Long objects primitive fields. Both have an almost identical definition. LongObjectType contains all the methods that describe how the database deals with Long fields.
public class LongObjectType {
while LongType overrides LongObjectType and only modifies one method to say that it processes primitives.
public class LongType extends LongObjectType { ... @Override public boolean isPrimitive() { return true; } }
Hope this helps.
Gray Sep 27 '11 at 17:28 2011-09-27 17:28
source share