Polymorphism, one of the three characteristics of object-oriented programming

polymorphic

Simple understanding

The different states of something at different times
For example:

Water:
Solid, liquid, gaseous
Solid water is water, liquid water is water, and gaseous water is water
Fruits:
Paramita, banana, durian
Parami is a fruit, banana is a fruit, durian is a fruit
The fruit is parami, so it's not allowed.
animal:
Dogs, tigers, cats, elephants
Dogs are animals, so there's no problem
Animals are dogs. That's not allowed.

The premise of polymorphism

        1,There should be inheritance
        2,There should be rewriting of methods.
            In fact, it's OK not to rewrite, but it's meaningless not to rewrite
            Animals have this method of eating, but the realization of each specific animal eating is different, realizing the unique attributes of different animals
        3,A reference to a parent class should point to a child class object

format

Parent class name f = new child class name (...);

Characteristics of polymorphic access members

1. Member variable
Compile to the left, run to the left
2. Construction method (initialization function)
When creating a subclass object, first access the construction method in the parent class and initialize the data of the parent class
3. Member method
Compile to the left and run to the right.
Because the member method is overridden, the access is shown on the right
4. Static member method
Compile and run on the left.
(since the members modified by static are related to classes, they are not rewritten here, so when running, they are accessed on the left)

Code example:

package com.shujia.wyh.day11;

class Fu3{
    int num = 100;
    public void show(){
        System.out.println("This is in the parent class show()method");
    }

    public static void fun(){
        System.out.println("This is static in the parent class fun method");
    }
}

class Zi3 extends Fu3{
    int num = 1000;

    @Override
    public void show(){
        System.out.println("This is in a subclass show()method");
    }

    public void show2(){
        System.out.println("This is subclass specific method 1");
    }
    public static void fun(){
        System.out.println("This is static in subclasses fun method");
    }
}

public class PolymorphicDemo1 {
    public static void main(String[] args) {
        //Polymorphism creates an object
        Fu3 f = new Zi3();//The parent class points to the child class object
        System.out.println(f.num);//100

        f.show(); // This is the show() method in the subclass
        f.fun();//This is the static fun method in the parent class
    }
}

Benefits of polymorphism

1. Polymorphism makes code extensible (guaranteed by inheritance)
2. Polymorphism can make code very maintainable (this is guaranteed by polymorphism)

Code example:

package com.shujia.rx.day12;

class Animal{
    String name;
    int age;

    public Animal() {
    }

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sleep(){
        System.out.println("sleep");
    }
    public void eat(){
        System.out.println("eat");
    }
}

class Dog extends Animal{
    public Dog() {
    }

    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void sleep() {
        System.out.println("The dog slept sideways");
    }

    @Override
    public void eat() {
        System.out.println("Dogs eat meat");
    }

}

class Cat extends Animal{
    public Cat() {
    }

    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void sleep() {
        System.out.println("The cat sleeps on its stomach");
    }

    @Override
    public void eat() {
        System.out.println("🐱Eat fish");
    }
}
//Improve with tools
class AnimalTool{
    public static void useAnimal(Animal animal){ //Animal animal=new Cat("little white", 9);
        //Taking advantage of the characteristics of polymorphic member access methods, the compiler looks at the left and the operation looks at the right. What is actually called is the method in the subclass object.
        animal.sleep();
        animal.eat();
    }
}

public class CatDogDemo {
    public static void main(String[] args) {
        //Keep a dog
        Dog d1 = new Dog("Xiao Huang",7);
        d1.sleep();
        d1.eat();
        useDog(d1);
        //Keep a cat
        Cat c1 = new Cat("Xiaobai",9);
        c1.sleep();
        c1.eat();
        AnimalTool.useAnimal(c1);

    }
    
    //Improve with methods
    public static void useDog(Dog dog){
        dog.sleep();
        dog.eat();
    }
}

Disadvantages of polymorphism

Polymorphism cannot access methods with the same method name in the parent class

What if I want to use unique methods in subclasses and have to use polymorphism?
1) do not use polymorphism, create sub class objects and call methods, but create objects again, and open up space in heap memory, which is likely to cause waste of resources.
2) Considering this problem, java provides a technology for us to use: downward transformation

Downward transformation

Casts a reference from a parent class to a reference from a child class
Format:

Subclass class name variable name = (subclass class name) reference of parent class;

be careful:
It is required that the transformed class has an inheritance relationship with the parent class reference, and this class is used when creating polymorphism at the beginning.

Code example:
Downward transformation cat and dog case

class Animal2{
    public void eat(){
        System.out.println("eat");
    }
}

class Dog2 extends Animal2{
    @Override
    public void eat() {
        System.out.println("Dogs eat meat");
    }

    public void lookDoor(){
        System.out.println("Janitor");
    }
}

class Cat2 extends Animal2{
    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }

    public void catchMouse(){
        System.out.println("Cat catches mouse");
    }
}

public class PolymorphicDemo4 {
    public static void main(String[] args) {
        //Create an object in polymorphic form
        Animal2 a = new Dog2();
        a.eat();
//        a.lookDoor();

        //Transition down to access methods unique to subclasses
        Dog2 d = (Dog2) a;
        d.eat();
        d.lookDoor();

        //ClassCastException class conversion exception
        Cat2 c = (Cat2) a; // At the moment, there is still a Dog2 object in the memory. The memory diagram is as follows:
        c.catchMouse();
    }
}


Code example:
Cases of different food cultures in different places

package com.shujia.wyh.day11;

/*
        Cases of different food cultures in different places
            Person
                eat()
            SouthPerson
                eat()
            NorthPerson
                eat()

 */
class Person{
    public void eat(){
        System.out.println("eat");
    }
}

class SouthPerson extends Person{
    @Override
    public void eat() {
        System.out.println("Southerners eat rice");
    }

    public void playMaJiang(){
        System.out.println("Southerners play mahjong");
    }
}

class NorthPerson extends Person{
    @Override
    public void eat() {
        System.out.println("Northerners eat pasta");
    }

    public void bath(){
        System.out.println("Northerners take a bath");
    }
}

public class PolymorphicDemo5 {
    public static void main(String[] args) {
        //Create southerner object
        Person p = new SouthPerson();
        p.eat();
//        p.playMaJiang();
        //Downward transformation
        SouthPerson sp = (SouthPerson) p;
        sp.eat();
        sp.playMaJiang();

        //Create northerner object
        Person p2 = new NorthPerson();
        p2.eat();
//        p2.bath();
        //Downward transformation
        NorthPerson np = (NorthPerson) p2;
        np.eat();
        np.bath();
    }
}

Keywords: Java Back-end

Added by Spitfire on Mon, 14 Feb 2022 08:02:18 +0200