15-polymorphism

Polymorphism

Polymorphism is the third major feature of object-oriented. Polymorphism is a concept extended on the basis of inheritance, which means that the mutual conversion between parent and child classes can be realized;

Introduction to polymorphism

The basic concept
of polymorphism: There are two modes of realization of polymorphism in java:

  • Method polymorphism
    • Method overloading: the same method name can implement different functions according to the type or number of parameters passed in;
    • Method override: the same method may have different implementations depending on the subclass used;
  • Object polymorphism: conversion processing between parent and child instances'
    • Object upward transformation: parent class parent class instance = child class instance, automatic conversion
    • Object downward transformation: subclass subclass instance = (subclass) parent class instance, forcibly complete the conversion

From the actual transformation processing, in most cases, the most consideration must be the upward transformation of the object (90%), and the downward transformation of the object often uses the special functions of the subclass (the subclass can perform functions on the parent class). When expanding), there are some cases where transformation is not considered (String class).

Object upward transformation (the uniformity of receiving or returning parameters)

The processing of object transformation belongs to polymorphism, and this feature must be realized on the basis of inheritance;
what is the main use of upward transformation?
Upgrading can achieve a unified design of parameters , why not use overload resolution because of the need to make a maintainable design

Object downcast

Upward describes some common characteristics, and downward describes the special definition environment of the subclass itself.
But what needs to be clear is that it is not a safe thing, because the upward transformation must be performed before the downward transformation;
the main meaning of the downward transformation is to call the subclass function.

instanceo keyword

In order to ensure the correctness of down-casting, it is often necessary to make a judgment before the transformation, to judge whether an instance is an object of a certain class, through instanceof syntax;
the judgment returns a boolean type, if it is True, the instance is an object of the specified class ;
对象 instanceof 类
If you want to perform the downward transformation of the object, it is best to judge once;

Guess you like

Origin blog.csdn.net/MARVEL_3000/article/details/111400659