Accessing methods through array elements only accesses methods defined in animal,
The methods defined in tiger and fish cannot be called, such as Statement Animal[2].swim (); When
A type conversion is required to access these methods, as shown in the following procedure.
1 Public classdynamicmethoddemo2{2 Public Static voidMain (String args[]) {3Animal []animal=Newanimal[3];4animal[0]=NewAnimal ();5animal[1]=NewTiger ();6animal[2]=NewFish ();7DynamicMethodDemo2 dm=NewDynamicMethodDemo2 ();8Dm.move (animal[0]);9Dm.move (animal[1]);TenDm.move (animal[2]); One } A voidMove (Animal Animal) { - //making judgments about object types - if(Animal instanceof Tiger) the (Tiger) animal). Tigerrun (); - Else if(Animal instanceof Fish) - (Fish) animal). Swim (); - Elseanimal.sleep (); + } -}
Mainly look at the move method, themove method first determine which class object is the animal object, by the judge to perform a different
Method. The instanceof operator is used in the judging process , which is an operator used to determine the type of an object. When judging
After its type, the type conversion is made, and the original type can be called to invoke its class-specific method.
Parent class variable access subclass methods in Java need to use type conversion (instenceof) keyword/type judgment/