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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With