英文:
Why isn't this method overridden?
问题
为什么输出中有值2和10?
难道myMethod方法没有被覆盖吗?
是的,如果我将Test类中方法的访问修饰符从private更改为任何其他修饰符,输出将和我预期的一样 - 2和20。但我认为子类的方法的可访问性至少应与父类的方法一样可访问 - 这是唯一的条件(与访问修饰符有关)来覆盖该方法。
public class Test {
private int myMethod(int x){return x;}
public static void main(String[] args) {
Test aTest = new Test();
Test aChild = new Child();
System.out.println(aTest.myMethod(2));
System.out.println(aChild.myMethod(10));
}
}
class Child extends Test{
public int myMethod(int x){return 2*x;}
}
英文:
Why are the values 2 and 10 in the output?
Isn't myMethod method overridden?
Yes, if I change the access modifier of the method in the Test class from private to any other, the output will be as I expected it - 2 and 20. But I thought that the method of the child class should be at least as accessible as the method of the parent class - this is the only condition (related to access modifiers) to override the method.
public class Test {
private int myMethod(int x){return x;}
public static void main(String[] args) {
Test aTest = new Test();
Test aChild = new Child();
System.out.println(aTest.myMethod(2));
System.out.println(aChild.myMethod(10));
}
}
class Child extends Test{
public int myMethod(int x){return 2*x;}
}
答案1
得分: -2
因为Test
中的myMethod
是私有的,而Child
类无法看到它。
英文:
Because myMethod
in Test
is private and Child
class doesn't see it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论