Link to home
Start Free TrialLog in
Avatar of chaitu chaitu
chaitu chaituFlag for India

asked on

what will be the output and why

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??



Avatar of petmagdy
petmagdy
Flag of Canada image

because null will not lead the complier to call which method of the 3 defined in this case as if null is accepted as a parameter for the 3 methods, in order to correct this situation if for example u want to call ( void m1(StringBuffer t) ) then u have to do this:

  a.m1( (StringBuffer) null);



Avatar of chaitu chaitu

ASKER

in ur case if i remove below method class compiled fine;
void m1(StringBuffer t)
 {
  System.out.println("StirngBuffer");
 }

at that time also

u said "because null will not lead the complier to call which method of the 3 defined in this case as if null is accepted as a parameter for the 2 methods"

how the compiler decided it should go to only to exception argument paameter;

ASKER CERTIFIED SOLUTION
Avatar of suprapto45
suprapto45
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok when u commented  void m1(StringBuffer t) the left 2 methods the parameters Exception and Throwable it happened that (Exception is based on throwable), in this case the Child class has more periority when to chose a target method thats why it decided to call void m1(Exception t)