How decalaring methods final, if they are not supposed to be overridden, help in JIT compilation

Let’s say you have a class that looks like this:

public class Demo {
    public void method() {
        // call printMessage
        printMessage();
    }
 
    public void printMessage() {
        System.out.println("Hello World");
    }
}

The call to printMessage could be “inlined” in the following way by JIT compiler:

public class Demo {
    public void method() {
        // call printMessage
        System.out.println("Hello World"); // <-- inlined
    }
 
    public void printMessage() {
        System.out.println("Hello World");
    }
}

(This is actually not done on the level of Java (not even on bytecode level) but during JIT-compilation, but the example above illustrates the concept of inlining.)

Now consider what would happen if the printMessage method was overloaded by another class,

like this:

class SubDemo extends Demo {
    public void printMessage() {
        System.out.println("Something else");
    }
}

Now if the compiler inlined the call to Demo.printMessage it would be stuck with System.out.println(“Hello World”); which would be wrong in case the object was actually an instance of SubDemo.
However, if the method was declared final this would not under any circumstances be the case. If the method is “final” it means that it can never be overridden with a new definition, thus, it is safe to inline it!

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *