can a local override final method?

橙三吉。 提交于 2019-12-10 21:25:22

问题


public class Test  {  

    public static void main(String args[]){
        Test t = new Test();
        t.inner();

    }
    public final void print() { 
        System.out.print("main"); 
    }      

    public void inner() {       
        class TestInner {           
            void print(){
                System.out.print("sub");                
            }

        }
        TestInner inner =new TestInner();
        inner.print();
        print();
    }
}

Out put : submain

Question : the method print() in class Test is final and is accessible to local class , but still local class is a able to define print() method again how?

If we declare private final x() in super class, it is not accessible in sub class so we can define x() in sub class.

If we declare public final x() in super class, it is accessible in sub class so we can not define x() in sub class.

Can anybody explain ?


回答1:


The inner class is not overriding the final method.

The inner class would have to extend the outer class for it to be able to override a method from the outer class.

The two classes are separate and unrelated to each other, other than the outer class contains the inner one.




回答2:


Because the TestInner class doesn't extend the Test class, so it has its own namespace that is separate.

There is no trick to it, it isn't overwriting the Test classes print method.




回答3:


The inner class is not overriding the final method.

The inner class would have to extend the outer class for it to be able to override a method from the outer class.

The two classes are separate and unrelated to each other, other than the outer class contains the inner one.



来源:https://stackoverflow.com/questions/14005474/can-a-local-override-final-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!