简体   繁体   中英

Is every method in Java overridable

Is every method in Java overridable? I know that in C# methods defined as virtual can be overriden, how was this implemented in Java?

Not every method is overridable: you cannot override methods that are final , private and static .

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. Of course changing static method to public or protected will still not allow you to override it.

final, static and private methods are not overridable. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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