为什么内部类可以重写私有的最终方法?
2022-08-31 15:00:17
我想知道将私有方法声明为 final 是否有意义,我认为这没有意义。但是我想象有一个排他性的情况,并编写了代码来弄清楚它:
public class Boom {
private void touchMe() {
System.out.println("super::I am not overridable!");
}
private class Inner extends Boom {
private void touchMe() {
super.touchMe();
System.out.println("sub::You suck! I overrided you!");
}
}
public static void main(String... args) {
Boom boom = new Boom();
Boom.Inner inner = boom.new Inner();
inner.touchMe();
}
}
它编译并工作。“我应该让touchMe()最终”我想并做到了:
public class Boom {
private final void touchMe() {
System.out.println("super::I am not overridable!");
}
private class Inner extends Boom {
private void touchMe() {
super.touchMe();
System.out.println("sub::You suck! I overrided you!");
}
}
public static void main(String... args) {
Boom boom = new Boom();
Boom.Inner inner = boom.new Inner();
inner.touchMe();
}
}
它也有效并告诉我
chicout@chicout-linlap:~$ java Boom
super::I am not overridable!
sub::You suck! I overrided you!
为什么?