0

Why upcast?

I understand why one would downcast. That functions similarly to changing a float to an int. However, why upcast? What is the benefit? And what is the result from the example if you call a.print() after upcasting from B?

23rd Mar 2017, 3:35 PM
Alexander Strickland
Alexander Strickland - avatar
2 Answers
+ 14
In general you upcast to have more precise results, e.g. for divisions: int i= 5; int j = 2; System.out.println(i/j); // outputs 2 double result = i / (double) j; System.out.println(result); // outputs 2.5
23rd Mar 2017, 4:34 PM
Tashi N
Tashi N - avatar
+ 14
Be careful with downcasting, IF the compiler let's you do this, it will just cut off the decimal places.
23rd Mar 2017, 4:36 PM
Tashi N
Tashi N - avatar