我有这个测试代码示例:
public class Test { private static class Test3 { private void print1() { System.out.println("1"); } } private static class Test4 extends Test3 { private void print1() { System.out.println("2"); } } public static void main(String[] args) { System.out.println("Overriden call to private method ----------------"); OuterTest.Test1 test1 = new OuterTest.Test1(); OuterTest.Test2 test2 = new OuterTest.Test2(); OuterTest.Test1 test12 = new OuterTest.Test2(); test1.invokeOverriden(); test2.invokeOverriden(); test12.invokeOverriden(); System.out.println("Call to private method from parent class ----------------"); test1.invokeNotOverriden(); test2.invokeNotOverriden(); test12.invokeNotOverriden(); System.out.println(" Some magic ----------------"); Test3 test3 = new Test3(); Test4 test4 = new Test4(); Test3 test34 = new Test4(); test3.print1(); test4.print1(); test34.print1(); } } class OuterTest { public static class Test1 { public void invokeOverriden() { print1(); } public void invokeNotOverriden() { print1(); } private void print1() { System.out.println("1"); } } public static class Test2 extends Test1 { @Override public void invokeOverriden() { print1(); } private void print1() { System.out.println("2"); } } }
首先,一切都按我的想法进行:
Overriden call to private method ---------------- 1 2 2
然后,如果我调用未实现的父方法,继承类的私有(private)方法就会消失。它可以解释为“所有私有(private)方法都是最终的并且对派生类隐藏”,因此 invokeNotOverriden()
不知道 Test2 类中的方法的任何信息:
Call to private method from parent class ---------------- 1 1 1
最后,在静态类中,当我调用非静态私有(private)方法时,一些魔法突然出现:
Some magic ---------------- 1 2 1
我预计这里是1 2 2
。为什么我错了?
最佳答案
在some magic
部分中有1 2 1
,因为私有(private)方法是在没有多态性的情况下解析的,编译器创建对包含在声明的类型变量中的方法的调用,在您的情况下Test3
。在 Test3
中将 print1
声明为非私有(private)(因此,在 Test4
中,因为禁止收紧方法的访问修饰符)并查看多态性操作,因此您将得到预期的 1 2 2
。
考虑更短的示例:
class Test {
private static class Test3 {
private void print1() {
System.out.println("non-polymorphic 1");
}
void polymorphic() {
System.out.println("polymorphic 1");
}
}
private static class Test4 extends Test3 {
private void print1() {
System.out.println("non-polymorphic 2");
}
void polymorphic() {
System.out.println("polymorphic 2");
}
}
public static void main(String[] args) {
Test4 t4 = new Test4();
t4.print1();
t4.polymorphic();
System.out.println("======");
Test3 t34 = new Test4();
t34.print1();
t34.polymorphic();
}
}
<小时/>
澄清 ...我对此答案的评论:多态性对于访问数据字段无效,仅对于方法有效。考虑:
private static class Test3 {
int i = 1;
}
private static class Test4 extends Test3 {
int i = 2;
}
public static void main(String[] args) {
Test4 t4 = new Test4();
System.out.println(t4.i);
System.out.println("======");
Test3 t34 = new Test4();
System.out.println(t34.i);
}
尽管i
声明为非私有(private),t34.i
值是1
。
关于java - 重写(非)静态类中的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59965765/