File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Please explain how output of this program came? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Please explain how output of this program came?" Watch "Please explain how output of this program came?" New topic
Author

Please explain how output of this program came?

Gaurav Guleria
Greenhorn

Joined: May 16, 2010
Posts: 2

OUTPUT:
Alpha:foo Beta:foo Beta:bar Beta:bar


God Loves Fun!!
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10451
    
    8

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


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Gaurav Guleria
Greenhorn

Joined: May 16, 2010
Posts: 2
Thanks Rob!.I will make me acquaint with the question posting rules.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain how output of this program came?