Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism! correct me if i am wrong.

 
Sanjana Sharma
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i have a polymorphic reference to refer to a subtype object with an overriding method, the complier just checks whether the method is present in the super class or not.

But the JVM comes into picture while runtime and invokes the subtype method ( for which the object was actually created )

Now I see an example where the superclass method declares a checked exception in the method but the sub class method( overriding method) doesn't.
Now if the superclass reference is to refer the subtype object with the overriding method, I see a compiler error - unreported exception. Why is this..? Is it because the complier just checks for the "presence " of the method in the super class..?

I am confused..!
 
Henry Wong
author
Marshal
Pie
Posts: 21122
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It would actually help if you posted a small example -- as I (and maybe others) am not exactly following you.

Henry
 
Sanjana Sharma
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Example taken from K&B SCJP book.
 
Henry Wong
author
Marshal
Pie
Posts: 21122
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh I see what you are getting at.

Sanjana Sharma wrote:
Now I see an example where the superclass method declares a checked exception in the method but the sub class method( overriding method) doesn't.


This is perfectly legal, because throwing less exceptions doesn't mean that a subclass isn't IS-A super class. Maybe the subclass has error handling so doesn't need to throw that exception.

Sanjana Sharma wrote:
Now if the superclass reference is to refer the subtype object with the overriding method, I see a compiler error - unreported exception. Why is this..? Is it because the complier just checks for the "presence " of the method in the super class..?


Basically, there is a reason that you are using the super class reference right? Maybe you need to call code that doesn't know about the subclass. Regardless, it has to behave like the superclass. So, the compiler treats it as such..... Or you can say the compiler isn't smart enough.

Henry
 
Sanjana Sharma
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, i get it.

But if there was no exception declared at all..
The complier doesn't complaint right?

Here the overriding methods gets invoked ( JVM checks for the actual object type) ..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic