One, polymorphic
1, what is polymorphic?
Parsing: Different objects respond differently to the same operation
Features that have the ability to express multiple forms
2. Advantages of using polymorphism
Parsing: In order to achieve unified invocation
A small example:< the parent class type as a parameter >
Parent class (Pet) subclass (Gog,penguin) master Human (master) test Class (test)
Pet
Public abstract class Pet {public abstract void Eat ();}
Dog
public class Dog extends pet{ @Override public void Eat () { System.out.println ("Enough to eat Bones"); }
Penguin
public class Penguin extends Pet { @Override public void Eat () { System.out.println ("Penguin Eats Fish"); }
Master
public class Master { //parent class type as parameter public void feed (Pet pet) { pet.eat (); }}
Test
public static void Main (string[] args) { Master master=new master (); Pet pet=new Dog (); Master.feed (PET); }
Transformation of subclasses to parent class (upward transformation)
Rules:
① a reference to a parent class to a subclass object, which becomes an upward transformation, automatic type conversion
② a method that is called by a parent class reference variable is a child class that overrides or inherits a method of the parent class, not the parent class's method
③ a method that is unique to a subclass cannot be called through a parent class reference variable
Third, two ways to implement and use polymorphism in Java
① using a parent class as a method parameter
② using the parent class as a method return value
Iv. conversion of parent class to subclass (downward transition)
Assigns a reference to a subclass object to a parent class reference, called a downward transformation. Forced type conversions are required at this time
Five, instanceof operators
Grammar:
Object instanceof class or interface
This operator is used to determine whether an object belongs to a class or implements an interface with the result of true or false
Note:
① when using the instanceof operator, the object must be of the same type as the class or interface specified by the second parameter of Instanceof, or a compilation error will occur
②instanceof commonly used in conjunction with forced type conversions
Polymorphic (Java)