This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Please explain how output of this program came?  RSS feed

 
Gaurav Guleria
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

OUTPUT:
Alpha:foo Beta:foo Beta:bar Beta:bar
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gaurav,
Welcome to the Ranch.

In future, while posting code, please UseCodeTags
Also please do take out time to go through http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags next time. I've added them this time.

Because Beta.bar overrides Alpha.bar, both calls to a.bar("test") and b.bar('test") call Beta.bar. This behaviour is called polymorphism.

Beta.foo has a different signature from Alpha.foo. In class Alpha, the only method foo that takes a String is foo(String...). Because with a.foo("test") the reference type is Alpha the compiler does not know that the object is actually a Beta instance and also has foo(String). Therefore, it calls the only method it knows: foo(String...) which prints "Alpha:foo ".
In class Beta there are two methods called foo -- foo(String...) which is inherited from class Alpha and foo(String) which is newly declared. With b.foo("test") the reference type is Beta so the compiler finds both methods. In this case the most specific method is chosen. Methods with varargs are always the last choice so that's why foo(String) is chosen, and "Beta:foo " is printed.
 
Gaurav Guleria
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob!.I will make me acquaint with the question posting rules.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!