Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism, Autoboxing, and Implicit Conversions

Would you consider autoboxing in Java to be a form of polymorphism? Put another way, do you think autoboxing extends the polymorphic capabilities of Java?

What about implicit conversions in Scala?

My opinion is that they are both examples of polymorphism. Both features allow values of different data types to be handled in a uniform manner.

My colleague disagrees with me. Who is right?

like image 501
dbyrne Avatar asked Feb 18 '26 23:02

dbyrne


2 Answers

From Wikipedia:

Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B.

Implicit conversions in Scala are conversions. One object gets converted to another object.

Autoboxing is the creation of an object (again, a conversion).

Therefore, these are not polymorphism.

like image 78
Matthew Farwell Avatar answered Feb 21 '26 13:02

Matthew Farwell


I personally consider autoboxing as kind of a hack with sometimes unexpected results.

 Boolean b = null;
 boolean b2 = b; // oops

The tricky part of autoboxing is that it isn't really a cast, which (only) changes the type, but more of a value conversion.

like image 43
extraneon Avatar answered Feb 21 '26 11:02

extraneon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!