Java reference variables have two types, one is a compile-time type and one is a run-time type.
The compile time is determined by the type used when declaring the variable, such as fruit duotai;
The runtime is determined by the object that is actually assigned to the variable, such as Duotai=new Apple ();
This presents polymorphism.
Class Books {public String name= ' book ';p ublic Void Base () {System.out.println ("the");} public void Open () { System.out.print ("This is an ordinary book"), }} public class Java extends Books {public String Name= "Java"; public void Open () { System.out.println ("This is Java"); } public void Go () { System.out.println ("Java method"); public static void Main (string[] args) { Java book=new java (); Java java=new Java (); Java.open (); System.out.println ("-------------------------------"); Book Duotai=new Java (); Here, the output book, which represents the instance variable of the parent class accessed, is not Java, because the instance variable is not polymorphic, and the instance method is polymorphic System.out.println (duotai.name); This is the base () method inherited by the parent class duotai.base (); This is the subclass of its own method Duotai.open (); Compile-time is the parent class, there is no subclass method, so error //duotai.go (); }} This is Java-------------------------------Book books This is Java
Because the subclass is a special parent class, it is possible to assign the class directly to the parent reference variable without any coercion of type conversion, which is called upward transformation, the system completes automatically, the reference variable
You can only invoke methods of its compile-time type, even if the object does contain a run-time method. If you need to invoke a run-time method, you need to cast it to the runtime's type, using the type conversion operator = "(type) variable
Forcing a type conversion requires an inheritance relationship.
public class Conversiontest {object ob= "Hellow";//Compile As Object, run as String, inheritance relationship, can force type conversion string obstr= (String) ob;// The OB is indeed a subclass instance that runs through an object object=new Integer (5);//There is an inheritance relationship//But the run type is Integer, not the subclass instance type, so cannot cast, string str= (String) object;/ /failed, exception occurred//considered to be an exception, so the instanceof operator is used to determine whether cast public void instancetest () {if (object instanceof String) { String str= (String) object;}}
Java Review of Polymorphism