Java Review Notes Advanced 05: Polymorphism

polymorphic

1. Overview of polymorphism

1.1 What is polymorphism

Objects of the same type perform the same behavior and exhibit different behavioral characteristics;

1.2 Common forms of polymorphism

  • Parent type object name= new subclass constructor;

  • Interface object name= new implementation class constructor;

Member Access Characteristics in 1.3 Polymorphism

  • Method calls: compile to the left and run to the right (polymorphism focuses on behavior polymorphism)

    • Compile to see if there is a corresponding method in the parent class

    • Run, execute subclass method results

  • Variable calls: compile to the left, run to the left;

1.4 Polymorphic premise

  • Has inheritance/implementation relationship;

  • There are parent references to subclass objects;

  • Method Rewrite

public abstract class Animal {
    public String name = "Animal Prototype";
    public abstract void run();
}

public class Dog extends Animal{
    public String name = "Dog prototype";

    @Override
    public void run() {
        System.out.println("Dog is run");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal dog = new Dog();
        //Compile left, run right
        //Dog is run
        dog.run();
        System.out.println(dog.name);

        Animal cat = new Cat();
        cat.run();
        //Animal Prototype, Variable with Parent
        System.out.println(cat.name);
    }
}

2. Polymorphic Advantages and Problems

  • In polymorphic form, the right object is decoupled to facilitate extended maintenance.

    • Subclass objects on the right can be swapped without affecting other code

  • Definition method, using parent object, strong compatibility, receiving all subclass objects, reflecting polymorphic extensibility;

  • There are problems:

    • Give priority to parent, use unique method of subclass, error

public class Test {
    public static void main(String[] args) {
        Animal dog = new Dog();
        go(dog);
        
        Cat cat = new Cat();
        go(cat);
        
        //dog and cat work equally well in go()
    }

    /**
     * Require that all animals be available
     * @param animal
     */
    public static void go(Animal animal){
        System.out.println("Start Up");
        animal.run();
        System.out.println("Time Out");
    }
}

3. Data conversion of reference data types under polymorphism

  • Automatic type conversion (from child to parent, small to large):

    • Variable conversion whose subclass object is assigned to the parent type;

  • Force type conversion (from parent to child):

    • Subclass object variable = (subclass) parent type variable;

    • Function: Solve the disadvantage of polymorphism, and realize the function of calling subclasses

      • 		//Automatic Type Conversion
                Animal a = new Dog();
                a.run();
        
                //Mandatory Type Conversion
                Animal b = new Cat();
                b.run();
                //b Cast from parent type to subtype
                Cat cat = (Cat) b;
                //To subtype, you can use a unique method
                cat.eatFish();
    • Post-transition type and object real type are not the same, type exception ClassCastException

      • //Force type conversion, compile phase error-free (inheritance or implementation relationships can be enforced), runtime error may occur; Type Exception ClassCastException
        //Dog dog = (Dog) b;

    • Java recommends using instanceof judgment before casting

      • /**
             * Require that all animals be available
             * The type of animal passed in is unknown
             * @param animal
             */
            public static void go(Animal animal){
                if (animal instanceof Dog){
                    Dog dog = (Dog) animal;
                    dog.lookDoor();
                }else if (animal instanceof Cat){
                    Cat cat = (Cat) animal;
                    cat.eatFish();
                }
            }

4. Polymorphic synthesis

public interface USB {
    void connect();
    void unConnect();
}

public class KeyBoard implements USB{
    private String name;

    public KeyBoard(String name) {
        this.name = name;
    }

    @Override
    public void connect() {
        System.out.println(name+"Successful Connection");
    }

    /**
     * Unique function
     */
    public void keyDown(){
        System.out.println(name+"Type characters");
    }

    @Override
    public void unConnect() {
        System.out.println(name+"Successfully pulled out");
    }
}

public class Mouse implements USB{

    Other as above

    /**
     * Unique function
     */
    public void dbClick(){
        System.out.println(name+"click the icon");
    }
}

public class Computer {
		Other as above
    /**
     * Provide USB device installation interface
     */
    public void installUSB(USB usb){
        usb.connect();
        //Judging Subclass Type and Implementing Function Strongly
        if (usb instanceof KeyBoard){
            KeyBoard keyBoard = (KeyBoard) usb;
            keyBoard.keyDown();
        }else if (usb instanceof Mouse){
            Mouse mouse = (Mouse) usb;
            mouse.dbClick();
        }
        usb.unConnect();
    }
}
public class Test {
    public static void main(String[] args) {
        Computer computer = new Computer("Machinist T58");
        computer.start();

        KeyBoard keyBoard = new KeyBoard("PHILIPS");
        //Insert Keyboard
        computer.installUSB(keyBoard);

        Mouse mouse = new Mouse("Logitech");
        computer.installUSB(mouse);
    }
}

 

Tags: Java

Posted by Ryokotsusai on Sun, 21 Aug 2022 23:10:31 +0300