aspose file tools*
The moose likes Beginning Java and the fly likes Polymorphism! correct me if i am wrong. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphism! correct me if i am wrong." Watch "Polymorphism! correct me if i am wrong." New topic
Author

Polymorphism! correct me if i am wrong.

Sanjana Sharma
Greenhorn

Joined: Jan 08, 2011
Posts: 29
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
Sheriff

Joined: Sep 28, 2004
Posts: 18990
    
  40


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

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sanjana Sharma
Greenhorn

Joined: Jan 08, 2011
Posts: 29


Example taken from K&B SCJP book.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18990
    
  40

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

Joined: Jan 08, 2011
Posts: 29
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) ..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polymorphism! correct me if i am wrong.