Home>Article>Java> How to understand java polymorphism

How to understand java polymorphism

王林
王林 forward
2020-06-19 16:59:59 2388browse

How to understand java polymorphism

1. Overview of polymorphism

Polymorphism is the third major feature of object-oriented after encapsulation and inheritance.

Understanding of the meaning of polymorphic reality:

Real things often take on multiple forms, such as students. Students are a type of human being, so a specific classmate Zhang San is both a student and a human being. There are two forms.

(Related tutorial recommendations:java introductory program)

As an object-oriented language, Java can also describe multiple forms of a thing. If the Student class inherits the Person class, a Student object is both a Student and a Person.

Polymorphism is reflected in the fact that parent class reference variables can point to subclass objects.

Prerequisite: There must be a child-parent class relationship.

Note: When calling a method using a polymorphic parent class reference variable, the overridden method of the subclass will be called.

Definition and usage format of polymorphism

父类类型 变量名=new 子类类型();

2. Characteristics of members in polymorphism

1. Polymorphic member variables: Compile and run to see Left

Fu f=new Zi(); System.out.println(f.num);//f是Fu中的值,只能取到父中的值

2. Polymorphic member methods: Compile and run on the left, run on the right

Fu f1=new Zi(); System.out.println(f1.show());//f1的门面类型是Fu,但实际类型是Zi,所以调用的是重写后的方法。

(Video tutorial recommendation:java video tutorial)

3. Polymorphic transformation

Polymorphic transformation is divided into two types: upward transformation and downward transformation.

1. Upward transformation: Polymorphism itself is a process of upward transformation

Usage format:

父类类型 变量名=new 子类类型();

Applicable scenarios: When there is no need to face subclass types, pass Improve scalability, or use the functions of the parent class to complete the corresponding operations.

2. Downward transformation: A subclass object that has been upwardly transformed can use the format of forced type conversion to convert the parent class reference type to the subclass reference type.

Use format:

子类类型 变量名=(子类类型) 父类类型的变量;

Applicable scenarios: When you want to use the unique functions of subclasses.

The above is the detailed content of How to understand java polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:what is method in java Next article:what is method in java