Overriding private methods in Java

You can’t override a private method, but you can introduce one in a derived class without a problem. This compiles fine:

class Base
{
   private void foo()
   {
   }
}

class Child extends Base
{
    private void foo()
    {
    }
}

Note that if you try to apply the @Override annotation to Child.foo() you’ll get a compile-time error. So long as you have your compiler/IDE set to give you warnings or errors if you’re missing an @Override annotation, all should be well. Admittedly I prefer the C# approach of override being a keyword, but it was obviously too late to do that in Java.

As for C#’s handling of “overriding” a private method – a private method can’t be virtual in the first place, but you can certainly introduce a new private method with the same name as a private method in the base class.

Leave a Comment