Polymorphic explanation and example code of C + + / Java inheritance class

Polymorphic explanation of C + + / Java inheritance classes

People who have studied C + + and Java know that both of them can carry out object-oriented programming, and the three characteristics of object-oriented programming are encapsulation, inheritance and polymorphism. Today, let's briefly understand the differences between C + + and Java in polymorphism.

First, let's look at a case.

C++

The above two classes are simple. Let's take a look at their test code and results.

It can be seen that all representations are the behavior of the parent class, whether it is the same attribute or overridden method. It should be noted here that if the child class hides the member function of the parent class, all member functions with the same name (overloaded functions) in the parent class are hidden. If you want to access the hidden function in the parent class, you need to access it through the parent class name (dog. Animal:: output();).

In the case of polymorphism, we access the behavior of the parent class. How can we access the functions of the child class? The answer is to define virtual functions, which we will explain later in the blog.

Now let's look at the performance of Java.

Java

A subclass also defines the same attribute as the parent class and overrides a method of the parent class. Let's take a look at its test method and test results.

It can be seen from here that there are differences between Java and C + +. The properties of Java represent the behavior of the parent class, but the rewritten method is the behavior of the child class, and C + + is all the behavior of the parent class.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>