英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论