wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Polymorphism" Watch "Polymorphism" New topic
Author

Polymorphism

Rohan Amin
Greenhorn

Joined: Mar 19, 2008
Posts: 15
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

Joined: Feb 10, 2008
Posts: 179

The code works fine.
Why do you think that it should generate an exception?


-kolli
Rohan Amin
Greenhorn

Joined: Mar 19, 2008
Posts: 15
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

Joined: Apr 02, 2008
Posts: 823

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.


Regards, Sud.
SCJP 5 ScjpFAQ JLS
Rohan Amin
Greenhorn

Joined: Mar 19, 2008
Posts: 15
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

Joined: Apr 02, 2008
Posts: 823

You are welcome
 
 
subject: Polymorphism