1. A reference to a parent type can point to an object of a subtype:
Parent p = new Child ();
2. When invoking a method using polymorphic mode, first check whether the method is in the parent class, if not, compile the error, and if so, call the subclass of the same name method.
3. Static statics methods are special cases, static methods can only inherit, cannot override override, and if the subclass defines a static method with the same name, it only acts as a hidden effect on the parent class method. The version of the call with whom the reference is made.
4. Using polymorphism, you can only use methods that override the parent class, and if the method is not overridden only in the parent class definition, the method of the parent class is called.
5. If you want to invoke a method in a subclass that is not in the parent class, you need to cast the coercion, as in the example above, convert p to a reference to the child type.
6. Up type conversion (upcast): Converts a subtype to a parent type, does not need to display the specified, that is, does not need to add the preceding parentheses and the parent class type name.
7. Down type conversion (downcast): Converts the parent type to a subtype, and for a downward type conversion, it must be explicitly specified, that is, the coercion type conversion must be used. And the reference of the parent type must point to the object of the subclass, that is, to whom to convert.
9. Example:
1 Public classpolytest2 {3 Public Static voidMain (string[] args)4 {5 6 //Up type conversion7Cat cat =NewCat ();8Animal Animal =Cat;9 animal.sing ();Ten One A //Down type conversion -Animal A =NewCat (); -Cat C =(Cat) A; the c.sing (); - c.eat (); - - + //Compile Error - //calling a method that does not exist in the parent class with a parent class reference + //Animal a1 = new Cat (); A //a1.eat (); at - //Compile Error - //downward type conversion can only be turned to the object type pointed to - //Animal a2 = new Cat (); - //Cat c2 = (Dog) A2; - in - to } + } - classAnimal the { * Public voidSing () $ {Panax NotoginsengSystem. out. println ("Animal is singing!"); - } the } + classDog extends Animal A { the Public voidSing () + { -System. out. println ("Dog is singing!"); $ } $ } - classCat extends Animal - { the Public voidSing () - {WuyiSystem. out. println ("Cat is singing!"); the } - Public voidEat () Wu { -System. out. println ("Cat is eating!"); About } $}View Code
The polymorphism of Java learning notes