Java basic knowledge notes 4--polymorphism

Polymorphism

Overview

Polymorphism is the third characteristic of object-oriented after encapsulation and inheritance.
In life, for example, the actions of running, kittens, puppies and elephants, run differently. Another example is the movement of flying. Insects, birds and airplanes are different when flying. It can be seen that the same behavior can be embodied in different forms through different things. Polymorphism describes such a state.

definition

Refers to the same behavior with multiple different manifestations.

premise

  1. Inherit or realize [choose one of two]
  2. Method rewriting [meaning: no rewriting, meaningless]
  3. The parent class reference points to the child class object [format embodiment]

Code

Polymorphism is reflected in the code, in fact, it is just one sentence: the parent class reference points to the child class object.

format:

Parent class name object name = new subclass name();

or

Interface name object name = new implementation class name();

Member variable and method access rules

Member variables

1. Access member variables directly through subclass objects:
whoever is on the left side of the equal sign will give priority to whoever is used, and if not, look up.
2. Indirect access to member variables through member methods:
whoever belongs to the method will be used first, and if not, look up.

Same as inheritance.

Member method

Whoever is new on the right will give priority to whoever is new. If not, look up.

Same as inheritance.

Formula

Member variables: compile to the left, and run to the left.

Member method: compile and look at the left, run and look at the right.

The benefits of polymorphism

Insert picture description here

Downcast and upcast

Insert picture description here

instanceof keyword

In order to avoid the occurrence of ClassCastException, Java provides the instanceof keyword to check the type of reference variables, the format is as follows:

1. Variable name instanceof data type
2. If the variable belongs to this data type, return true.
3. If the variable does not belong to the data type, return false.

public class Test {
    
    

    public static void main(String[] args) {
    
    
        Animal animal = new Dog();
        animal.eat();
        givePet(animal);
        givePet(new Cat());
    }

    public static void givePet(Animal animal){
    
    
        if(animal instanceof Dog){
    
    
            Dog d = (Dog) animal;
            d.protectHouse();
        }
        if(animal instanceof Cat){
    
    
            Cat c = (Cat) animal;
            c.catchMouse();
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/108684068