Woodstock Blog

a tech blog for general algorithmic interview questions

[Question] Overriding Private Method

Question

link

Can we overriding private method in Java?

Analysis

Overriding private methods in Java is invalid because a parent class’s private methods are “automatically final, and hidden from the derived class”. source

Solution

You can’t override a private method, but you can introduce one in a derived class without a problem. Read more below.

Code

not a problem

public class OverridePrivateMethod {
    private void foo() {
    }
}

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

add @Override annotation and get error

public class OverridePrivateMethod {
    private void foo() {
    }
}

class Child extends OverridePrivateMethod {
    @Override
    private void foo() {
    }
}