This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain how output of this program came?

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

OUTPUT:
Alpha:foo Beta:foo Beta:bar Beta:bar
 
Maneesh Godbole
Saloon Keeper
Posts: 10971
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • 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
Pie
Posts: 20388
46
Chrome Eclipse IDE Java Windows
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob!.I will make me acquaint with the question posting rules.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic