简体   繁体   English

Java中的每个方法都是可覆盖的

[英]Is every method in Java overridable

Is every method in Java overridable? Java中的每个方法都是可覆盖的吗? I know that in C# methods defined as virtual can be overriden, how was this implemented in Java? 我知道在定义为虚拟的C#方法中可以覆盖,这是如何在Java中实现的?

Not every method is overridable: you cannot override methods that are final , private and static . 并非每个方法都可以覆盖:您不能覆盖finalprivatestatic

below is a small sample of what this means in practice: 以下是这在实践中意味着什么的一个小样本:

class Base {
    public final void fun1() {
    }

    private void fun2() {
        System.out.println("Base::fun2");
    }

    public void fun2Call() {
        fun2();
    }        
}

class Rextester extends Base
{  
    /*
    @Override
    public void fun1() { // compile error, because Base::fun1 is final
    } 
    */

    // if @Override is uncommented, it will protect you from overriding private methods
    //  otherwise you will not get any compile time error.
    //@Override 
    private void fun2() {
        System.out.println("Rextester::fun2");
    }    

    public static void main(String args[])
    {
        Base b = new Rextester();
        b.fun2Call(); // will output Base::fun2,
                      // if you change private to protected or public 
                      // then you will see Rextester::fun2 in output
    }
}

I think static method overriding is the same case as private method overriding, at least you will get similar behaviour. 我认为static方法覆盖与private方法覆盖的情况相同,至少你会得到类似的行为。 Of course changing static method to public or protected will still not allow you to override it. 当然,将static方法更改为publicprotected仍然不允许覆盖它。

final, static and private methods are not overridable. final,static和private方法不可覆盖。 All the rest are. 其余的都是。

final prevents overriding because, well, this is what it was meant for. 最终防止覆盖,因为,这就是它的意思。

static means to belong to the Class and not the instance. static意味着属于Class而不是实例。

private - no visibility, no overriding. 私人 - 没有知名度,没有超越。

Also, JIT is happier when it sees methods as non-overridable, since it means monomorphic dispatch of the method, which means it is a perfect candidate for inlining the method, as there is no other instance that can override this one. 此外,JIT在将方法视为不可覆盖时更快乐,因为它意味着方法的单态分派,这意味着它是内联方法的完美候选者,因为没有其他实例可以覆盖此方法。 This might be of no importance to you right now, but it speeds up the method pretty much. 这对你来说可能并不重要,但它几乎加速了这个方法。

No, not all are. 不,不是全部。 Method(s) marked with either of final , private , static modifiers are not overridable at all. 标有finalprivatestatic修饰符的方法根本不可覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM