Java – Do I have to override all versions of overloaded functions in inherited classes?

Do I have to override all versions of overloaded functions in inherited classes?… here is a solution to the problem.

Do I have to override all versions of overloaded functions in inherited classes?

Because I need a cancelable OutputStreamWriter, id did the following

public class CancelableStreamWriter extends OutputStreamWriter {

public CancelableStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException {
        super(out, charsetName);
        stuff
    }

public CancelableStreamWriter(OutputStream out) {
        super(out);
        stuff
    }

public CancelableStreamWriter(OutputStream out, Charset cs) {
        super(out, cs);
        stuff
    }

public CancelableStreamWriter(OutputStream out, CharsetEncoder enc) {
        super(out, enc);
        stuff
    }

public void write(int c) throws IOException {
        if (myCancelCondition) {
             cancel stuff
        }
        super.write(c);
    }

public void write(char cbuf[], int off, int len) throws IOException {
        if (myCancelCondition) {
             cancel stuff
        }
        super.write(cbuf, off, len);
    }

public void write(String str, int off, int len) throws IOException {
        if (myCancelCondition) {
             cancel stuff
        }
        super.write(str, off, len);
    }
}

I

was wondering if I really have to override all overloaded versions of write functions. Or is it possible like:

    public void write(WHATEVERARGS) throws IOException {
        if (myCancelCondition) {
             cancel stuff
        }
        super.write(WHATEVERARGS);
    }

Same as constructor.

Maybe this isn’t the most elegant method at all, but I can’t use a wrapper object because the type that owns the class is OutputStreamWriter and I can’t change it.

Solution

Keep your approach.

Unfortunately, this is not possible, and there is no shortcut to covering all methods (or “overriding” all constructors). Java methods and constructors must have fixed parameters. This is because of language design.

Fortunately, most IDEs support generating such code with a few clicks. You just need to select all methods and constructors you want to override (and then add your custom functionality).

Related Problems and Solutions