这是我的代码
package alpha ;
class A1
{
static class A11
{
private
final // WHAT IS THE EFFECT OF THIS MODIFIER?
void fun ( String caller )
{
System . out . println ( "A11:\t" + caller ) ;
}
}
static class A12 extends A11
{
private void fun ( String caller )
{
super . fun ( caller + caller ) ;
}
}
public static void main ( String [ ] args )
{
A12 a12 = new A12 ( ) ;
a12 . fun ( "Hello" ) ;
}
}
我发现无论在 A1.A11 中有没有最终的 mdifer,程序都能编译和运行。
我可以理解,如果没有 final 修饰符,A1.A12 可以看到并因此覆盖 fun 方法。它是私有(private)的,但它们属于同一类,因此不存在可见性问题。
我不明白为什么它与 final 修饰符一起使用。 A1.A12 中的重写不应该被禁止吗?
这是带有最终修饰符的程序的输出
java alpha/A1
A11: HelloHello
如果它只是简单地忽略其他有趣的方法那么
- 编译器会不会提示 super 引用
- A11 不会出现在输出中
最佳答案
您的方法是私有(private)的。
将它们的可见性更改为 protected 以查看预期行为,即只有当方法 protected 、公共(public)或默认可见性时,覆盖的概念甚至存在。
做这样的事情——
class A1
{
static class A11
{
public
final // WHAT IS THE EFFECT OF THIS MODIFIER?
void fun ( String caller )
{
System . out . println ( "A11:\t" + caller ) ;
}
}
static class A12 extends A11
{
public void fun ( String caller )
{
super . fun ( caller + caller ) ;
}
}
public static void main ( String [ ] args )
{
A12 a12 = new A12 ( ) ;
a12 . fun ( "Hello" ) ;
}
}
现在将抛出编译时异常
fun(java.lang.String) in A1.A12 cannot override fun(java.lang.String) in A1.A11; overridden method is final
关于java - final 修饰符的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863558/