JavaRush /Java Blog /Random EN /Expansion/narrowing of reference types: different sources...
Core
Level 35
Екатеринбург

Expansion/narrowing of reference types: different sources - different interpretation

Published in the Random EN group
Good afternoon. There is a suspicion of an error in the JavaRush lectures. Let there be a Parent class and a Child class inherited from it. Let there be the following lines of code: Parent parent = new Child; Child child = (Child) parent; According to the lecture of the level 12 course, lesson 1 (1. Polymorphism and overriding), paragraph 5) (Type casting.) the first line is a narrowing, and the second is an expansion( in the lecture , Cow is the parent, Whale is the heir) But this is not true. Everything is exactly the opposite. The meaning of what is described is clear: in the first line we created an object of type Child and limited its use only to the methods described in the Parent class. But this is an extension and therefore such a reduction occurs implicitly. And in the additional materials of level 10 it was said: Your text to link...
Extension means moving from a more specific type to a less specific type, i.e. transition from children to parents. In our example, the conversion from any heir (Child, Child2) to the parent (Parent) is an extension, a transition to a more general type. Similar to the case with primitive types, this transition is made by the JVM itself if necessary and is invisible to the developer, that is, it does not require any additional effort, since it always succeeds: you can always access an object generated from an inheritor by the type of its parent. Parent p1=new Child(); Parent p2=new Child2(); In both lines, variables of type Parent are assigned a value of a different type, which means a conversion occurs. Since this is an extension, it is done automatically and is always successful.
The second line of my example, on the contrary, according to the same add. materials is a narrowing that requires an explicit indication of the type in parentheses. And in the lecture it is interpreted as an extension, which is probably wrong. Please explain. I don't want to have a double conflicting view of type casting. Below is a fragment of the lecture. lecture fragment There were still suspicions of errors in the (previous) lectures. Where should I write about this? I didn't find it in the FAQ.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION