Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : How to force a given protected method to be overloaded by children classes?

The father class is not and cannot be made abstract. The method to overload is protected so interfaces cannot be used there.

Having these two restrictions in mind is it possible to do it?

like image 468
mors Avatar asked Dec 20 '12 19:12

mors


3 Answers

You can't force the method to be overridden - that's what abstract methods are for (which you've stated isn't an option).

One possibility is to make the method in the base class throw an UnsupportedOperationException. Then, the subclass must override it in order to prevent the error being thrown. That way, you can at least detect if the method has been overridden.

For example:

public class Father {
    public void method ( ) {
        throw new UnsupportedOperationException( );
    }
}

public class Child1 extends Father {

}
public class Child2 extends Father {
    public void method ( ) {
        // Do something useful here...
    }
}

Calling Child1.method() will throw UnsupportedOperationException, indicating that it hasn't overridden Father's method(). Calling Child2.method() will not throw the exception, meaning that it has overridden method().

like image 135
Mac Avatar answered Sep 24 '22 06:09

Mac


You could throw an UnsupportedOperationException from the parent. That won't help at compile time but will at run time.

like image 44
Todd Murray Avatar answered Sep 22 '22 06:09

Todd Murray


Since abstract is not an option you could have the method throw a NotImplementedException. This is a more explicit exception then UnsuppotedOperationException.
Note: This will not prevent the code from compiling and will only throw an exception at run time.

Public Clazz {
    public void methodToOverride(){
        Throw new NotImplementedException();
    }
}

Some Examples implemntations:
Apache
Sun
sharkysoft.com

like image 36
Mike Rylander Avatar answered Sep 25 '22 06:09

Mike Rylander