Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism (invoking methods) - K&B book.

 
Pawel Nowacki
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ;)

(peace)

 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tagged for reference. Thanks Omar
 
Pawel Nowacki
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic