简体   繁体   中英

Java upcasting and downcasting and inheritance

Let say there is one superclass and two subclasses.

Why Java doesn't allow this scenario:

B -> A (A is superclass of class B)
C -> A
ObjectC c = (ObjectC)(ObjectA)b;

This way I could map common properties from object b to object c.

With (ObjectA)b you have an expression, if evaluated results in a reference of type ObjectA (ObjectA ab = (ObjectA)b). The actual type of the instantiated object (in memory) does not change, only the handle with you hold it (the reference) changes. You cannot cast that reference to ObjectC , because the underlying object instance (originally b) is of type ObjectB .

Let's say we allowed what you wrote in the question ObjectC c = (ObjectC)(ObjectA)b . If you evaluate that you'd get a reference of type ObjectC to the instantiated object b. Let's say ObjectC has a method called run(), but of course, ObjectB does not have to have a run() method. What would happen when you call c.run() ?

If you want to map common properties from object b to object c you have to use their common base-class and put common properties there.

Edited with better explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM