• 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:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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
 
I didn't like the taste of tongue and it didn't like the taste of me. I will now try this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic