0

In the below code, the child class object calls its getBankName() method but instead, the private method getBankName() of parent class is invoked.

public class Bank {
    private void getBankName() {
        System.out.println("Bank");
    }
    public static void main(String[] args) {
        Bank bank = new MyBank();
        bank.getBankName();
    }
}

class MyBank extends Bank {
    public void getBankName() {
        System.out.println("MyBank");
    }
}

Further, if I change the access specifier of parent's method to public, then it works fine(child object calls its own method and prints 'MyBank'). Why is the invocation getting affected just because of the access specifier of the parent method??

hitesh
  • 39
  • 5
  • 1
    As a note, Java convention is that `get` methods _return_ a value; instead of `void`, the type should be `String`, and you should `return "Bank"`. – chrylis -cautiouslyoptimistic- May 30 '20 at 07:04
  • Java does not support private method override because of security and encapsulation issues, check: https://stackoverflow.com/questions/2000137/overriding-private-methods-in-java. – PatrickChen May 30 '20 at 07:23
  • Very bad design. A super Class should never know a subclass – Jens May 30 '20 at 07:24
  • Design is not my concern here for this question, just trying to make out why its happening. – hitesh May 30 '20 at 07:32

1 Answers1

0

Private methods can't be overridden; they're entirely different items, like redeclared (shadowing) fields.

When the visibility of a method is not private, the compiler uses the invokevirtual instruction, which is responsible for finding the appropriate override and executing it. However, for a private method, the compiler uses invokespecial (see "Notes"), which explicitly does not allow for overrides.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152