Class Typecasting Rules
In an inheritance hierarchy, you can cast an object to any of its parent or child classes in the hierarchy tree. This can be done with the same syntax used for primitives ((newType) oldObject
). Keep in mind, however, that you will get an Exception
at runtime if you try to do illegal casting (for example, cast a Square
to a Circle
).
If you try to typecast an object to a subtype, it is called downcasting, or narrowcasting. Generally, it is considered bad practice to downcast unless it is absolutely necessary in your code. If you try to typecast an object to a superclass type, then it is called upcasting, or wide casting. Most polymorphism concepts are applied with the help of upcasting in a program.
1// JavaScript does not have explicit type casting in the same way as Java.
2// However, for demonstration purposes, the idea can be shown with class inheritance:
3class Main {
4 constructor() {
5 let rect = new Rectangle(5,6);
6
7 // Upcasting (implicitly)
8 let shape = rect;
9
10 // Downcasting (not directly possible in JS, but for demonstration)
11 let rect2 = shape;
12
13 // This is also valid
14 let shape2 = new Rectangle();
15
16 // But this would be invalid (and will throw an error if tried)
17 // let rect3 = new Shape();
18 }
19}
It is not allowed in Java to typecast to other classes outside of the superclass and subclasses set. In those cases, you will need a ModelMapper
which will give you class A
given B
or class B
given A
regardless of any inheritance relationship between A
and B
.
It's too complicated to go through ModelMapper
now, so we are leaving it out of this series. However, feel free to go and check the documentation yourself if you are curious.