How Java Compiler Generate Code for Overloaded and Overridden Methods?

Here is a simple Java example showing Polymorphism: overloading and overriding.

Polymorphism means that functions assume different forms at different times. In case of compile time it is called function overloading. Overloading allows related methods to be accessed by use of a common name. It is sometimes called ad hoc polymorphism, as opposed to the parametric polymorphism.

class A {
	public void M(int i){
		System.out.println("int");
	}
 
	public void M(String s){
		//this is an overloading method
		System.out.println("string");
	}
}
 
class B extends A{
	public void M(int i){
		//this is overriding method
		System.out.println("overriden int");
	}
}
public static void main(String[] args) {
	A a = new A();
	a.M(1);
	a.M("abc");
 
	A b = new B();
	b.M(1234);
}

From the compiler perspective, how is code generated for the correct function calls?

Static overloading is not hard to implement. When processing the declaration of an overloaded function, a new binding maps it to a different implementation. During the type checking process, compiler analyzes the parameter’s real type to determine which function to use.

Dynamic overloading allows different implementations of a function to be chosen on the run-time type of an actual parameter. It is a form of dynamic dispatch.

Dynamic dispatch is also used to implement method overriding. The overridden method are determined by real object type during run-time.

To understand dynamic dispatch, there is a post about object layout in memory.

1 thought on “How Java Compiler Generate Code for Overloaded and Overridden Methods?”

Leave a Comment