Detailed explanation of Java polymorphism (1)

polymorphism

The concept of polymorphism

The so-called polymorphism, in layman's terms, is a variety of forms. The specific point is to complete a certain behavior. When different objects complete it, different states will be produced .

for example:

 In the popular "modern documentary" at this time, MacArthur always has different evaluations of various "celebrities", which can also be regarded as polymorphism. 

In general: the same thing, happening to different objects, will produce different results .

Polymorphic Realization Conditions

To achieve polymorphism in Java, the following conditions must be met, all of which are indispensable:

1. Must be under the inheritance system (upward transformation)

2. The subclass must rewrite the method in the parent class

3. Call the rewritten method through the reference of the parent class

Polymorphism: When the code is running, when different objects are passed, the methods in the corresponding classes will be called.

for example:

class Animal {
    String name;
    int age;

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

    public void eat() {
        System.out.println(name + "吃饭");
    }
}

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

    @Override
    public void eat() {
        System.out.println(name + "吃骨头");
    }
}

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

    @Override
    public void eat() {
        System.out.println(name + "吃鱼干");
    }
}

public class TestAnimal {
    //编译器在编译代码的同时,并不知道要调用Cat还是Dog中的eat方法
    //等程序运行起来后,形参a引用的具体对象确定后,才知道调用哪个方法
    //注意:此处的形参类型必须是父类类型才可以
    public static void eat(Animal a) {
        a.eat();
    }

    public static void main(String[] args) {
        Dog dog = new Dog("小七", 2);
        Cat cat = new Cat("元宝", 1);
        eat(dog);
        eat(cat);
    }
}

When the caller of the class writes the eat method, the parameter type is Animal (parent class), and at this time, the method does not know and does not pay attention to which type (which subclass) the current a reference points to. At this time, the eat method called by the reference of a may have many different manifestations ( related to the instance referenced by a ), and this behavior is called polymorphism.

rewrite

Rewrite (override): Also known as coverage. Rewriting means that the subclass rewrites the implementation process of the parent class that is non-static, non-private, non-final, and non-constructive methods. The return value and formal parameters cannot be changed, that is, the shell remains unchanged, and the core is rewritten ! The advantage of rewriting is that subclasses can define their own specific methods according to their needs. That is to say, the subclass can implement the method of the parent class as needed.

Rules for Method Overriding

1. When a subclass rewrites the method of the parent class, it must generally be consistent with the prototype of the parent class method: that is, the return value type method name (parameter list) must be exactly the same

2. The return value type of the overridden method can be different, but it must have a parent-child relationship

3. The access rights cannot be lower than the access rights of the overridden methods in the parent class. For example: if the parent class method is modified by public, the method rewritten in the subclass cannot be declared as protected

4. The methods of the parent class modified by static, private, and final cannot be rewritten

5. The rewritten method can be explicitly specified with the @Override annotation. With this annotation, we can do some legality checks. For example, if you accidentally misspelled the method name (for example, the above eat is wrongly written as aet), then the compiler will find that there is no aet method in the parent class, and it will display a compilation error

The difference between rewriting and overloading

point of difference override Overload (overlaod)
parameter list must not be modified must be modified
return type Must not be modified (unless a parent-child relationship can be formed) can be modified
access qualifier Can't make tighter restrictions (can lower restrictions) can be modified

That is: method overloading is a polymorphic expression of a class, and method rewriting is a polymorphic expression of a subclass and a parent class

Design Principles for Rewriting

For classes that have already been put into use, try not to modify them. The best way is: redefine a new class to reuse common content and add or change new content.

For example: a few years ago, mobile phones could only make calls and send text messages, and the caller ID could only display the number, but today's mobile phones can not only display the phone number, but also display the region, name, etc. when the caller ID is displayed. In this process, we should not modify the original old class, because the original class may still be used by users. The correct way is to create a new mobile phone class and rewrite the method of the caller ID. This is meet today's needs .

 Static binding: also known as early binding (early binding), that is, at compile time, which method to call is determined according to the actual parameter type passed by the user. Typical representative function overloading.

Dynamic binding: also known as late binding (late binding), that is, at compile time, the behavior of the method cannot be determined, and it is necessary to wait until the program is running to determine which method to call.

Guess you like

Origin blog.csdn.net/asdssadddd/article/details/132289405