This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes what will be the output and why Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "what will be the output and why" Watch "what will be the output and why" New topic
Author

what will be the output and why

kesava chaitanya
Ranch Hand

Joined: Aug 15, 2001
Posts: 140
package example;

class dup
{
public static void main(String[] args)
{
System.out.println("Hello World!");
dup a=new dup();
a.m1(null);
}
void m1(Throwable t)
{
System.out.println("Throwable");
}
void m1(Exception t)
{
System.out.println("Exception");
}
void m1(StringBuffer t)
{
System.out.println("StirngBuffer");
}

}


when i run this class i am gettiing this exception

Error(9,5): reference to m1 is ambiguous; both method m1(java.lang.Exception) in class example.dup and method m1(java.lang.StringBuffer) in class example.dup match

if i remove this method

void m1(StringBuffer t)
{
System.out.println("StirngBuffer");
}

application is compiled fine;

when i run the class

i am getting o/p

Hello World!
Exception

but i assumed o/p will be

Hello World!
Throwable

why??
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

When resolving overloaded methods, the compiler chooses the most specific applicable overload. Because Exception is a subclass of Throwable the m1(Exception) overload is "more specific". On the other hand, there's no way to decide which of Exception or StringBuffer matches better, so with all three methods, you get the compile error.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: what will be the output and why
 
Similar Threads
How this program compiled & outputs after modifying variable with "final" prefix?
About args to main()
Doubt in StirngBuffer
static method
static method overriding in same class