Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism

 
Rohan Amin
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The K&B covered the following example for polymorphism.
.
The following compiles but later gives an exception.

But the book does not cover this example.

.
The following compiles but gives no exception. I guess it has something to do with the type of object the reference variable refers to. This is the complete code



Please let me know about this.
 
Ravikanth kolli
Ranch Hand
Posts: 179
Chrome Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code works fine.
Why do you think that it should generate an exception?
 
Rohan Amin
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well i am not sure as to whether it should or should not throw exception. My guess is that it basically points to the sub class object and so even if it is being referred to by super class instance it gets downcasted. Well i just wanted to confirm whether my understanding is correct or not because this particular example has not been covered in the book but the topic actually starts with a similar example. Animal a = new Dog();
 
sudipto shekhar
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rohan Amin wrote:
.
The following compiles but later gives an exception.



.
The following compiles but gives no exception.
Please let me know about this.


The first code will definitely produce an exception..


This is because in SuperClass sc=new SuperClass() the reference variable sc refers to an object of SuperClass and it can not be cast to subtype object. The next code SuperClass sc=new SubClass() is correct as a reference variable of super type can refer to an object of subclass which is correct and hence it is also correct to cast the variable to the subtype(downcasting).
I hope this explains what you are seeking . Also correct me if I am wrong.

 
Rohan Amin
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well thats what i think. I think both the codes get past the compiler but at runtime the actual object is checked and so at the first case it fails whereas in the second case it works and so the program works.

Thanks for your reply.
 
sudipto shekhar
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic