Chapter 13 three characteristics of object-oriented in JavaSE topic - polymorphism

Posted by philippe2 on Wed, 09 Feb 2022 10:39:07 +0100

1. Polymorphic introduction

  • Meaning: method or object has many forms, which is the third feature of object-oriented. Polymorphism is based on encapsulation and inheritance;

  • Business scenario: please write a program. There is a feed (feeding method) in the master class, which can complete the information of the director feeding animals;

  • Train of thought analysis

/*
1,Create parent class - Food
	1.1,Create subclass - Fish inherits Food;
	1.2,Create subclass - Bone inherits Food;

2,Create parent Animal
	2.1,Create subclass - Dog inherits Animal
	2.2,Create subclass - Cat inherits Animal
	
3,Create Master class - feed method
*/
  • example
//1. Create parent Animal
package com.taobao;

public class Animal {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//1.1. Create subclass - Dog inherits Animal
package com.taobao;

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
}

//1.2. Create subclass - Cat inherits Animal
package com.taobao;

public class Cat extends Animal{
    public Cat(String name) {
        super(name);
    }
}

//2. Create parent class - Food
package com.taobao;

public class Food {

    //1. Food name attribute definition
    private String name;

    //2. Constructor
    public Food(String name) {
        this.name = name;
    }

    //3. Generate a get/set method
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//2.1. Create a subclass - Fish inherits Food;
package com.taobao;

public class Fish extends Food {
    public Fish(String name) {
        super(name);
    }
}

//2.2. Create a subclass - Bone inherits Food;
package com.taobao;

public class Bone extends Food {
    public Bone(String name) {
        super(name);
    }
}

//3. Create Master class
package com.taobao;

public class Master {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //1. The owner fed the dog bones

    public void feed(Dog dog,Bone bone){
        System.out.println("master" + name + "to" + dog.getName() + "eat" + bone.getName());
    }
    //2. The owner fed the dog bones

    public void feed(Cat cat,Fish fish){
        System.out.println("master" + name + "to" + cat.getName() + "eat" + fish.getName());
    }
}

//4. Create the main method and call the above class
package com.taobao;

public class hello {
    public static void main(String[] args) {

        //1. Master Tom gave rhubarb a big stick bone
        Master tom = new Master("Tom");
        Dog dog = new Dog("chinese rhubarb");
        Bone bone = new Bone("Big stick bone");

        tom.feed(dog,bone);

        //2. Tom, the owner, gave the kitten yellow croaker
        Cat cat = new Cat("Kitten");
        Fish fish = new Fish("Yellow croaker");

        tom.feed(cat,fish);
    }
}
  • Operation results

  • traditional method
    • Problem: code reusability is not high, and it is not conducive to code maintenance
    • Solution: polymorphic solution

2. Polymorphism overview

  • Meaning: method or object has many forms, which is the third feature of object-oriented;
2.1 compile time polymorphism - polymorphism of methods

① Determining the target method during compilation

② Implemented by overloading

③ The method name is the same, but the parameters are different

public int sum(int n1,int n2){
	return n1 + n2;
}
public int sum(int n1,int n2,int n3){
	return n1 + n2 + n3;
}
2.2. Runtime polymorphism - polymorphism of objects (key)

① The compilation type and running type of an object can be inconsistent;

② The compilation type is determined when defining the object and cannot be changed;

③ The operation type can be changed;

④ For the compilation type, see the left side of the = sign when defining, and for the operation type, see the right side of the = sign;

// You can make the reference of the parent class point to the object of the child class
Animal animal = new Dog()
// The compilation type of Animal is Animal and the running type is Dog
animal = new Cat()
// The compile type of Animal is still Animal, and the run type is Cat
2.3 analysis of polymorphic memory

① Analysis of polymorphic memory at compile time

Subsequent updates

② Analysis of runtime polymorphic memory

Subsequent updates

2.4. Polymorphic use
  • Premise: polymorphic types see themselves as parent types

① Member variable: uses the of the parent class

② Member method: subclass method is used due to rewriting

③ Static member: it is loaded with the loading of the class. Who calls and returns who

3. Polymorphism of methods

  • Scenario: Rewriting and overloading reflect method polymorphism
Overload embodiment method
  • example
package com.taobao;

public class hello {
    public static void main(String[] args) {
        // Overloading reflects polymorphism: when different methods are passed in, different sum methods will be called to reflect polymorphism
        B b = new B();
        System.out.println("Sum of two parameters:"+b.sum(1,2));
        System.out.println("Sum of three parameters:"+b.sum(1,2,3));
    }
}

class A { // Parent class
    public void say(){
        System.out.println("A say() Method called...");
    }
}

class B extends A{ // Subclass
    public int sum(int n1,int n2){
        return n1 + n2;
    }
    public int sum(int n1,int n2,int n3){
        return n1 + n2 + n3;
    }
}
  • Operation results

3.2. Method rewriting reflects polymorphism
  • example
package com.taobao;

public class hello {
    public static void main(String[] args) {
        // Method rewriting reflects polymorphism: due to method rewriting, the corresponding method will be located automatically
        A a = new A();
        B b = new B();
        a.say();
        b.say();
    }
}

class A { // Parent class
    public void say(){
        System.out.println("A say() Method called...");
    }
}

class B extends A{ // Subclass
    public void say(){
        System.out.println("B say() Method called...");
    }
    public int sum(int n1,int n2){
        return n1 + n2;
    }
    public int sum(int n1,int n2,int n3){
        return n1 + n2 + n3;
    }
}
  • Operation results

4. Polymorphism of objects (core)

4.1. Introduction cases of polymorphism
  • example
//1. Define parent class - Animal class
public class Animal {
    public void cry(){
        System.out.println("Animals are barking");
    }
}

//2. Define subclass - Dog class inherits Animal
public class Dog extends Animal {
    public void cry(){
        System.out.println("The dog barked...");
    }
}

//3. Define subclass - Cat inherits Animal
public class Cat extends Animal {
    public void cry(){
        System.out.println("kittens mew ...");
    }
}

//4. main method reference
public class poly2 {
    public static void main(String[] args) {
        //Experience object polymorphism

        //The compilation type of Animal is Animal, and the running type is Dog
        Animal animal = new Dog();
        //When this line is executed at runtime, the running type of animal is Dog, so cry is the cry of Dog
        animal.cry();

        //The compiling type of Animal is Animal, the running type is Cat, and the pointer points to Cat
        animal = new Cat();
        animal.cry();
    }
}
  • Operation results

  • matters needing attention:
    • P: Why is the compile type inconsistent with the run type
    • A: One needle multi-purpose:
      • A reference to a parent class can point to either a parent class or a child class;
      • If the cry method is not defined in animal, an error will be reported during compilation;
4.2. Multi state application scenarios
  • Polymorphism premise: two objects (classes) have inheritance relationship;

  • Example: using polymorphism can uniformly manage the feeding problem of the host and simplify the feed method

//1. Using polymorphic mechanisms
public class Mater {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //Polymorphism: the use of polymorphism mechanism can uniformly manage the feeding mechanism of the host
    //The compilation type of Animal is Animal, which can point to (receive) objects of subclasses of Animal
    //The animal compilation type is Food, which can point to (receive) the object of Food subclass
    public void feed(Animal animal,Food food){
        System.out.println("master" + name + "to" + animal.getName() + "eat" + food.getName());
    }
}


//2. Create subclass - Pig inherits the Animal class
public class Pig extends Animal {
    public Pig(String name) {
        super(name);
    }
}

//3. Create subclass - Rice inherits Food class
public class Rice extends Food {
    public Rice(String name) {
        super(name);
    }
}

//4. Write main method
public class Poly01 {
    public static void main(String[] args) {

        //1. Master Tom gave rhubarb a big stick bone
        Mater tom = new Mater("Tom");
        Dog dog = new Dog("chinese rhubarb");
        Bone bone = new Bone("Big stick bone");

        tom.feed(dog,bone);

        //2. Tom, the owner, gave the kitten yellow croaker
        Cat cat = new Cat("Kitten");
        Fish fish = new Fish("Yellow croaker");

        tom.feed(cat,fish);

        //3. The host Tom gave Huahua rice
        Pig pig = new Pig("tearful");
        Rice rice = new Rice("rice");
        tom.feed(pig,rice);
    }
}
  • Running result: when calling subclass methods with polymorphic parent class reference variables, the subclass rewritten methods will be called;

4.3 upward transformation
  • Find the method from the subclass. If there is one, call it. If there is no one, find the method from the parent class
    • All in all: you can call the subclass, you can call the parent class, and you can't call the special member & method of the subclass

essence:The reference of the parent class points to the object of the child class;
grammar:Parent type reference name = new Subclass type()  //Raise the child class as the parent class
 characteristic:The compilation type is shown on the left,The operation type is shown on the right.
    All members of the parent class can be called(Access rights must be observed);
    A unique member in a subclass cannot be called;
	The final operation effect depends on the concrete embodiment of the subclass;
  • example
//1. Create parent class Animal
public class Animal {
    String name = "animal";
    int age = 10;
    public void sleep(){
        System.out.println("sleep");
    }
    public void run(){
        System.out.println("run");
    }
    public void eat(){
        System.out.println("eat");
    }
    public void show(){
        System.out.println("hello world!");
    }
}

//2. Create subclass - Cat inherits Animal
public class Cat extends Animal {
    public void eat(){ //Method rewrite
        System.out.println("Cats eat fish");
    }
    public void catchMouse(){//cat specific methods
        System.out.println("Cat catches mouse");
    }
}


//3. Write main method to realize polymorphism
public class poly {
    public static void main(String[] args) {
        //Upward Transformation: the reference of the parent class points to the object of the child class
        Animal animal = new Cat();
        System.out.println("ok~~");

        //Note: you can call all members of the parent class (subject to access rights), but you cannot call members specific to the child class
        //	Because those members that can be called in the compilation stage are determined by the compilation type;
        //	The final operation depends on the specific implementation of subclasses (running types), that is, calling methods, starting with subclasses and then calling them, consistent with inheritance rules.
        animal.eat();
        animal.run();
        animal.show();
        animal.sleep();
    }
}
  • Running results: call eat, run and show to find cat subclasses first. Cat subclasses have eat method calls. If there are no run and show subclasses, look up. The unique methods in subclasses cannot be used

4. Downward transformation
  • Usage scenario: subclass objects that have been transformed upward before want to perform the unique functions of subclasses and restore them to subclass objects.

  • matters needing attention

    • ① Syntax: subclass type reference name = (subclass type) parent class reference;
    • ② You can only forcibly convert the reference of the parent class, not the object of the parent class;
      The reference of the parent class must be defined first, and then the parent class application is forced
    • ③ It is required that the reference of the parent class must point to the object of the current target type;
      Animal class references of cats cannot point to dogs
    • ④ After downward transformation, you can call all members in the subclass type;
  • example

public class hello {
    public static void main(String[] args) {
        //Upward Transformation: the reference of the parent class points to the object of the child class
        Animal animal = new Cat();
        //Downward Transformation: Cat is the compile type and Cat is the run type
        Cat cat = (Cat) animal;
        //Object animal1 = new Cat();  // It can be defined that object is the parent class of animal
        System.out.println("ok~~");
        animal.eat();
        animal.run();
        animal.show();
        animal.sleep();
        cat.catchMouse();
    }
}
  • Operation results

4.5. Dynamic binding mechanism (very important)
  • Java dynamic binding mechanism

    • 1. When an object method is called, the method turns to the memory address / running type of the object;
    • 2. When calling object properties, there is no dynamic binding mechanism. Where to declare and where to use
  • Introduction case

package com.taobao;

public class hello {
    public static void main(String[] args) {
        A a = new B();  //Upward transformation
        System.out.println(a.sum());
        System.out.println(a.sum1());
    }
}

class A {
    public int i = 10;
    public int sum(){
        return get1() +10;
    }

    public int sum1(){
        return i+10;
    }

    public int get1(){
        return i;
    }
}

class B extends A {
    public int i = 20;
    public int sum(){
        return i + 20;
    }
    public int sum1(){
        return i+10;
    }
    public int get1(){
        return i;
    }
}
  • Operation results

  • Example: when commenting the sum() and sum1() methods of subclasses
package com.taobao;

public class hello {
    public static void main(String[] args) {
        A a = new B();  //Upward transformation
        System.out.println(a.sum());
        System.out.println(a.sum1());
    }
}

class A {
    public int i = 10;
    public int sum(){
        return get1() +10;   //Whether get1 calls the parent class or the child class, the dynamic binding mechanism calls get1 of the child class
    }

    public int sum1(){
        return i+10;
    }

    public int get1(){
        return i+1;
    }
}

class B extends A {
    public int i = 20;
    public int get1(){
        return i;
    }
}
  • Operation results

Topics: Java objective-c