Java overloads and overrides _20150804
Overloading and rewriting are completely different syntax phenomena, the differences are as follows:
Overloading: A method that defines multiple methods with the same name but different parameter lists in a class, and determines which method to bind, depending on the number and type of arguments, at compile time.
Rewrite: Refers to a method defined in a subclass that is exactly the same as the parent class, and calls different methods depending on the type of the object (not the reference type) when the program is run.
Analyze the output of the following code:
Package Day04;class Super {public void F () { System.out.println ("Super.f ()");} } Class Sub extends Super {public void F () { System.out.println ("Sub.f ()");} } Class Goo {public void g (Super obj) { System.out.println ("G (Super)"); OBJ.F (); } public void g (Sub obj) { System.out.println ("G (sub)"); OBJ.F (); }} Class Test02 {public static void Main (string[] args) { Super obj = new Sub (); Goo Goo = new Goo (); GOO.G (obj);} }
Analysis of the above code, the output is:
G (Super)
Sub.f ()
Analysis:
First, overloading follows the so-called " compile-time binding " that determines which method should be called at compile time based on the type of the parameter variable , because the variable obj is the Super class
So, Goo G (super) is called to Output G (super) first.
Overrides follow the so-called " run-time bindings " that invoke methods at run time, based on the type of the actual object that the reference variable points to , because obj actually points to
is an object of sub-class sub, so the subclass-overridden F method is called, Sub.f ().
Summary: Overloading and rewriting do not have a relationship, but there are a lot of differences, this small example is a comprehensive summary of the difference between overloading and rewriting and essentials. Master This small example, for overloading and rewriting the basic master!!!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java overloads and Overrides _20150804