Home > Java > JavaBase > body text

Conversion problem between parent class and subclass in java

王林
Release: 2019-12-17 11:55:54
forward
3739 people have browsed it

Conversion problem between parent class and subclass in java

Example 1

The parent class forces the child class to rotate

Father f = new Father();
Son s = (Father)f;//出错 ClassCastException
Copy after login

Analysis:

Create an instance of the parent class and want to force Converting parent class objects into subclasses is not possible! In layman's terms, a real father can never pretend to be a son.

Online learning video tutorial sharing: java online tutorial

Example 2

"Fake" parent class forced to rotate subclass

Father f = new Son();
Son s = (Son)f;//可以
Copy after login

Analysis:

The parent class object refers to a subclass instance.

The properties unique to the Son class cannot be operated by f for the time being, because the Father class does not have the unique properties of the Son class (subclass).

Then create the subclass object s, which refers to the object that was forcibly converted from the parent class object f (actually it is a pretending Son, who was forcibly converted back to Son). At this time, you can pass s To operate the unique attributes of the subclass.

In layman's terms, a son is pretending to be his father. He is still a son after all, and his essence has not changed. He can still be forced to turn back into a son.

Example 3

Forced subclass conversion to parent class

Son s = new Son();
Father f = (Father)s;//可以
Copy after login

Analysis:

The subclass is converted to the parent class, but the unique attributes of the subclass object cannot be Using the f operation, f can operate on its non-specific properties (properties inherited from the parent class).

In layman’s terms, what a son and his father have in common is that they are both human beings. A son is a human being and inherits it from his father. They both have basic human behaviors, but a son can never be the same generation as his father. (Subclass type is converted to parent class type).

Recommended related articles and tutorials: java quick start

The above is the detailed content of Conversion problem between parent class and subclass in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!