最终修饰符的异常行为 [英] Unexpected Behavior wrt the final modifier

查看:80
本文介绍了最终修饰符的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

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的程序都可以编译并运行.

I have found that with or without the final mdifer in A1.A11 the program compiles and runs.

我可以理解,没有final修饰符,A1.A12可以看到并因此覆盖fun方法.它是私有的,但它们属于同一类,因此不存在可见性问题.

I can understand that without the final modifier, A1.A12 can see and thus override the fun method. It is private but they are in the same class so there is no visibility issue.

我不明白为什么它要与final修饰符一起使用.不应该禁止在A1.A12中进行覆盖吗?

I can not understand why it works with the final modifier. Should not the overriding in A1.A12 be prohibited?

这是程序的输出,其中有最后的修饰符

This is the output of the program with the final modifer in place

java alpha/A1
A11:    HelloHello

如果只是忽略了另一个有趣的方法,那么

If it was simply ignoring the other fun method then

  1. 编译器不会抱怨超级引用
  2. A11不会出现在输出中

推荐答案

您的方法是私有.

将其可见性更改为受保护"以查看预期的行为,也就是说,仅当该方法处于受保护状态,公共可见性或默认可见性时,甚至覆盖的概念都存在.

Change their visibility to protected to see expected behavior, that is, only when the method is protected, public or default visibility, the concept of overriding even exists.

做这样的事情-

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

这篇关于最终修饰符的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆