1. The Java reference variable has two types: one is the compile-time type, one is the runtime type, and the compile-time type is determined by the type used when declaring the variable, and the type of the runtime is determined by the object that is actually assigned to the variable. If the compile-time type and run-time type are inconsistent, the so-called polymorphism occurs;
2. The reference variable can only invoke the method of its compile-time type in the compile phase, but the runtime executes the method of its run-time type, which is the embodiment of the method polymorphism.
3, polymorphism is for the method, the property of the object is not polymorphic. When you access an object instance property by referencing a variable, the system always attempts to access the properties defined by the compile-time type, not the properties defined by the run-time type.
Example code:
Class Base {public int num = 9;public void base () {System.out.println ("base base ()");} public void info () {System.out.println ("Base info ()");}} Class Sub extends Base {public String num = "Sub class";p ublic void Sub () {System.out.println ("Sub Sub ()");} public void info () {System.out.println ("Sub info ()");}} public class Main {public static void main (string[] args) {base BC = new Base ()//BC Compile-time type and run-time type are basebc.base ();//output: Base Base () bc.info ();//output: Base info () System.out.println (bc.num);//output: 9Sub sc = new Sub ();//SC compile-time type and run-time type are subsc.base (); /output: base base () Sc.info ();//output: Sub info () sc.sub ();//output: Sub Sub () System.out.println (sc.num);//output: Sub classbase polymorphism = new Sub ();//polymorphism compile-time type is base, run-time type is subpolymorphism.base ();//output: Base base () Polymorphism.info () ;//output: Sub info () System.out.println (polymorphism.num);//output: 9}}
[Java Basic] Polymorphism