Mrab Ezreb Mrab Ezreb - 2 years ago 78
Java Question

Concrete subclass that does not override abstract methods from abstract class

Say that I have two, abstract methods in an abstract base class:

protected abstract void writeData(OutputStream stream);
protected abstract void writeData(Writer writer);

When I make an implementation, I have to override these methods so that when the data needs to be written, it knows how to do it.

What I need to know is if I can make a subclass only need to override ONE of the methods, instead of both of them.

Also, I want to know how to figure out which one of the methods is overrided.

Is this even possible?

Answer Source

The short answer is no.

The long answer is : An abstract method in an abstract class must be overridden in a sub-class. If you wan't to override only one of these methods in your subclass, the subclass will have to be declared as abstract as well. Such a subclass is pretty much useless if it does not have any static fields or methods because it cannot be instantiated and you cannot access instance fields or methods without an instance of the class.

That being said, Java 8 introduces the concept of default methods in an interface. You could convert your abstract class into an interface and mark writeData(OutputStream stream) and writeData(Writer writer) as default :

public interface DataWriter {
    public default void writeData(OutputStream stream) {

    public default void writeData(Writer writer) {

The above code is similar to an abstract class and different from a concrete class because it cannot be instantiated. While this solves your problem,I really don't see much value in doing something like this in the first place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download