Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism and casting

 
Sammy Bill
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i was expecting this to output A as the casting will give an A object then print will be called on A object, but the output was B.

Why?

Thanks.
Oussama
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's simple. The call will be polymorphic. Just look at this modified code

 
Sammy Bill
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it Thanks. the casting was tricky though. i thougth the casting will make it A a = new A();

Thanks.
 
Panagiotis Varlagas
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't matter what type the variable refering to the object is; what matters is of what class the object actually is.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic