Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism Object String

I didn't get to understand the polymorphism.

taking this example :

Object o = new String ("foo");

I can't do

o.substring (1,2)

can anyone explain this problem to me ?

like image 911
user_1330 Avatar asked Feb 03 '26 10:02

user_1330


2 Answers

This is a consequence of the Liskov Substitution Principle, which states (summarized):

If S and T are objects, and T is a subtype of S, then T may be used where S is expected.

String is-a subtype of Object, so if your assignment operation expects Object, then it will happily accept Object or any of its subtypes.

(Note: Object is not a String. All Strings are Objects, but not all Objects are Strings.)

This doesn't mean you get access to any of the subtype's methods. Given the inheritance hierarchy, an Object has no clue about any of its children's specific methods, nor can it - there is no way to inform an ancestor class of its descendant's capabilities. Because Object has no substring method associated with it, your code correctly results in a compilation failure.

(And it should, given that Object is the ancestor of all classes. There's no guarantee that any given Object is a String.)

The standing advice is to not use an overly inspecific object type (as you go up the hierarchy chain, the capabilities become less specific - you lose functionality as you go up to Object) to accomplish something specific to a more specific type.

like image 180
Makoto Avatar answered Feb 04 '26 22:02

Makoto


You are confusing dynamic and static typing with polymorphism.

Java is a statically typed language so the compiler recognizes that Object doesn't have a substring() method and throws an error. Polymorphism happens after the compilation, when the code is actually executed.

like image 31
Karol Dowbecki Avatar answered Feb 05 '26 00:02

Karol Dowbecki



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!