• Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphism at runtime  RSS feed

 
Shouvik Bhattacharya
Ranch Hand
Posts: 40
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys..


My question is if the two cases mentioned above are run independently then in case of case 1 I know that due to runtime polymorphism the sup reference variable will resolve to the SubClass() object and hence the method() in SubClass runs. But somebody please explain me the runtime mechanism involved for case 2 when a cast is also invloved.
 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think line 18 compiles. I've never seen that syntax before.
 
Shouvik Bhattacharya
Ranch Hand
Posts: 40
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apologies, my mistake..........I have edited line 18.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting does not do anything to the object that is being referenced. It is simply an instruction to the compiler to trust you that the object referenced is assignable to a variable of the cast type.

After the cast has been made the object is still the same, and your second example is not functionally different to your first. The cast is redundant though, the compiler doesn't need to trust you. It already knows the object is assignable to the super type variable.

The compiler will also not trust you blindly. If it knows a cast is invalid it will not let you do it.



That will fail because the compiler knows a String cannot be assigned to an Integer.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shouvik Bhattacharya wrote:
.....I have edited line 18.
Don't. It makes KS's post look meaningless if you edit the previous post.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As soon as the line with the cast is past, the object reverts to its original type. You can try ((Superclass)obj).method() but even that might not work.
 
Shouvik Bhattacharya
Ranch Hand
Posts: 40
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Shouvik Bhattacharya wrote:
.....I have edited line 18.
Don't. It makes KS's post look meaningless if you edit the previous post.


Edited it again to support KS' s post.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!