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?
2 odpowiedzi
+ 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
+ 14
Be careful with downcasting, IF the compiler let's you do this, it will just cut off the decimal places.