Reputation: 504
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 ?
Upvotes: 3
Views: 633
Reputation: 106400
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 String
s are Object
s, but not all Object
s are String
s.)
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.
Upvotes: 1
Reputation: 631
substring
is from the String
class, not the Object
class. So the below code will work:
String o = new String ("foo");
o.substring(1,2);
This code will not work:
Object o = new String ("foo");
o.substring(1,2);
Since String
inherits from Object
, String
can call Object
's methods, such as toString
. However, Object
does not inherit from String
, so an Object
cannot call String
's methods, such as substring
.
Upvotes: 1
Reputation: 73
First thing It's not polymorphism.
In Simple way, In your case o
object will only call methods which are defined in Object class. If String
class has overridden any method of Object
class then object o
will execute that method of String
class otherwise Object o
will call Its own method.
For example :
substring()
method is only defined in String
class So In this case your code will throw exception, however if you call equals()
, hashcode()
, toString()
methods (as these are defined in Object
class ) then definition inside String
class will get executed because String
Class has overridden these methods. And if any of the methods from object Class has not been overridden in its child class then definition inside Object class will get executed.
Upvotes: 1
Reputation: 44952
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.
Upvotes: 1