javainheritancemethodsmethod-hidingmember-hiding

Hiding methods in subclass


I have a abstract superclass with some implemented methods.

Is it possible to hide methods from this superclass in an subclass inheriting from this superclass? I don't want to have some methods visible from the superclass in some of the subclasses. Last but not least, is it possible to change the number of arguments for a method in the subclass which has the same name in the superclass?

Let's say we have a method public void test(int a, int b) in the superclass but now I want a method public void test(int a) in the subclass which calls the superclass function and the method from the superclass not visible anymore.


Solution

  • Is it possible to hide methods from this superclass in an subclass inheriting from this superclass?

    If you make the method private in the super class, it won't be visible in the subclass (or to any one else).

    If you need the method in the base class to be public however, there is no way of hiding it in the subclass by for instance overriding it with a private implementation. (You can't "reduce visibility", i.e. go from for instance public or protected to private in a subclass.)

    The best workaround is probably to override the method and throw for a runtime exception such as UnsupportedOperationException.

    is it possible to change the number of arguments for a method in the subclass which has the same name in the superclass?

    No, you can't change the signature. You can create another method with the same name and a different number of arguments but this would be a different (overloaded) method and the method in the base class would still be visible.