为什么这个方法没有被重写?

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

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.

huangapple
  • 本文由 发表于 2020年10月26日 02:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64527228.html
匿名

发表评论

匿名网友

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

确定