Daniel Watrous on Software Engineering

A Collection of Software Problems and Solutions

Software Engineering

Override Java Methods on Instantiation

Most Java programmers are very familiar with the mechanism to extend a class. To do this, you simply create a new class and specify that it extends another class. You can then add funtionality not available in the original class, AND you can also override any functionality that existed already. Imagine a simple class

public class Message {
    private String message;
 
    public Message(String message) {
        this.message = message;
    }
 
    public void showMessage() {
        System.out.println(message);
    }
}

Suppose you want these messages sent to the log too. You could extend the class as follows:

public class LoggedMessage extends Message {
    private String message;
 
    public Message(String message) {
        this.message = message;
    }
 
    public void showMessage() {
        Logger.getLogger(MyClass.class .getName()).info(message);
        System.out.println(message);
    }
}

Now you could create an instance of LoggedMessage rather than Message and have all messages logged in addition to just displaying them. Pretty neat, but there might be a better way.

Override on instantiation

Imagine that you only needed messages logged in one case. In other words, the Message class is sufficient in all cases except one. In that case, you can simply create an instance of Message that overrides this functionality. This is also referred to as an anonymous subclass.

Message loggedMessage = new Message () {
    @Override
    public void showMessage() {
        Logger.getLogger(MyClass.class .getName()).info(message);
        System.out.println(message);
    }
};

Why is this great? With this approach, you avoid adding another class with an uncommon use case to your software. You still have only one Message class. However, you still benefit from the modified behavior of a sub class.

Another use case would be when you want to use Message, but showMessage is frequently different. In other words, you would end up with many sub classes to accommodate all the use cases.

When to extend

If you find yourself copying and pasting this same override in many places, you should probably create a sub class one time. You may also find that the difference each time you override the method at instantiation differs by a parameter that could be injected. In that case, you should simply define an injection point in your class and let your DI framework provide you with a Message object that is configured the way you need it.

Leave A Comment