[Simple Java] How does the Java compiler generate code for the overload and override methods?

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.