File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Polymorphism (invoking methods) - K&B book. 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 (invoking methods) - K&B book." Watch "Polymorphism (invoking methods) - K&B book." New topic

Polymorphism (invoking methods) - K&B book.

Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
K&B book, page 99, there is this statement:

A reference variable's type determines the methods that can be invoked on
the object the variable is referencing.

Now, what is this have to do with the fact that Java dynamically choose method at runtime having the actual object as a key?
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Reference type restricts you from calling some methods, that is actually in given object.
run this code, you will get what it wants to say:

[EDIT: I had forget to write extends Super in BaseClass declaration as shown by Pawel.]

Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
Hmm, you must have forgot "extends Super " on BaseClass declaration.

Still, what you've said just proves my doubts - show method is not allowed to be used because of actual BaseClass object that is referenced by Super.
Im starting to think that im confusing compile and runtime... may it be the reason?
Omar Al Kababji
Ranch Hand

Joined: Jan 13, 2009
Posts: 357
suppose you have the following example :

and the following child class:

ofcourse polymorphism would work such as calling the foo() method:

however even if "child" points to a "Child" object the refrence is of type "Parent" so you can't write in your code

child.childMethod(); and the compiler will cause a compile time error, which is exactly what is meant by the reference type defines the method that can be invoked.

hope you got it ;)


Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
Tagged for reference. Thanks Omar

~Currently preparing for SCJP6
Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
ok, now i understand.

1. Reference variable indicates methods that can be invoked at compile time.
2. Actual object type indicates methods that can be invoked at runtime.

Those two things acts separately. And when i apply those two to my code i recieve a set of methods that actually can be invoked.
Thanks omar, Punit!
I agree. Here's the link:
subject: Polymorphism (invoking methods) - K&B book.
jQuery in Action, 3rd edition