为什么子对象调用父类的私有方法,而该私有方法包含主方法?

huangapple go评论75阅读模式
英文:

Why does a child object call private method of the super class having main method?

问题

在下面的代码中,子类对象调用了它的getBankName()方法,但实际上调用了父类的私有方法getBankName()。

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");
    }
}

此外,如果我将父类方法的访问修饰符更改为public,那么它就正常工作(子对象调用自己的方法并打印“MyBank”)。为什么仅仅因为父方法的访问修饰符影响了调用?

英文:

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??

答案1

得分: 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.

英文:

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.

huangapple
  • 本文由 发表于 2020年5月30日 14:43:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/62098811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定