[Simple Java] How does the Java compiler generate code for the overload and override methods?
The following is a simple example of polymorphism in Java: Method overloading and method overwrite;
Polymorphism means that the method has different forms in different timelines; during compilation, this is called method overloading; Method overloading allows the relevant method to be called by the same method name, this is sometimes called ad-hoc polymorphism;
package simplejava;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 class Q13 { public static void main(String[] args) { A a = new A(); a.M(1); a.M("abc"); A b = new B(); b.M(1234); }}
So how can the compiler generate method code so that it can be called correctly?
Static overload implementation is not difficult. When handling the declaration of overloaded methods, bind them to different implementations. During the type check, the compiler analyzes the parameter type to determine which method is called;
Dynamic overloading allows you to select different methods based on the actual parameter type during running. This is a form of dynamic Distribution (dynamic dispatch;
Dynamic Distribution (dynamic dispatch) can also be used to implement method coverage. The called method to be overwritten is determined by the actual object type during running;
For more information about dynamic dispatch, see the following link about the distribution of objects in memory:
Http://www.programcreek.com/2011/11/what-do-java-objects-look-like-in-memory/
Http://www.programcreek.com/2011/10/how-java-compiler-generate-code-for-overloaded-and-overridden-methods/.