• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Can anyone explain reason for this behaviour ?

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Have a look at following code:


Output of this sample is 'Hi'.

Can anyone explain logic behind this behaviour?

I was expecting it to be 'Hello' as object passed was actually of Class B but reference holder was of Class A.

Cheers!!
Gaurav Daga
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

The method a is overloaded and not overridden.
When you call b.a(a),it goes to class b and finds the a()ethod which is more appropriate.
out of two overloaded a()
that is 1. void a(A a) from class A
2. void a(B b) from class B

Void a(A a) is selected since reference of class a is sent as an argument.
When selecting overloaded method,jvm looks at the reference rather object.
Thats why it invoked method in class A and hence the output "Hi"

Thanks
Praveen SP
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

As you said in your class name, your example is about overloading, not overriding, so you cannot expect polymorphic behaviour. The method will be called based on the reference type, not the actual object type.
 
Gaurav Daga
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks both of you for your reply.

It means whenever method selection (for overloaded method), is to be done at that time JVM matches reference type of arguement not exact type of that object. Seems a bit strange to me. [:-(]

Anyways thanks for your prompt response.

~Gaurav Daga
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic