The realization principle of java polymorphism

The realization principle of java polymorphism

There are two ways to achieve polymorphism, one is compile-time polymorphism , and the other is run-time polymorphism ; compile-time polymorphism is achieved through method overloading, and run-time polymorphism is through method rewriting to be realized.

Method overloading means that there are multiple methods with
the parameters. Which method to call can be determined at compile time .

Overriding methods, subclasses override methods in superclasses. The reference variable of the parent class can not only point to
the , but also to the instance object of the subclass. When a reference of a parent class points to an object of a child class, only at runtime can determine which method to call .

The difference between Override and Overload

Overloading and overriding are different expressions of polymorphism in java.

Overloading is a manifestation of polymorphism in a class, which means that multiple
methods , but they have different number of parameters or different parameter types.
When using overloading, pay attention to the following points:
1. Overloading can only be distinguished by different method parameters. For example, different parameter types , different number of parameters , and different parameter order .
2. It cannot be overloaded by access rights, return types, and thrown exceptions.

Overriding means that the subclass function overrides the function in the parent class
1. The function name and parameters of the overridden method must exactly
match to achieve the effect of overriding;
2. The return value of the overridden method must be Consistent with the return value type of the
overridden method; 3. The exception thrown by the overridden method must be the same as the exception thrown by the overridden method,
or its subclass;
4. The overridden method cannot be private , Otherwise, a new method is just defined in its subclass, and it is not overridden.
5. The access modification permission of the subclass function should be greater than or equal to that of the parent class (public > protected > default > private). (important! ! ! )

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325511596&siteId=291194637