• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading a Method

 
swati aole
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I created one class 't' with overloaded method show(), when I call it with show(null) it gives compile time error saying 'ambiguous' reference, when there are two overloaded methods show(t a) and show (tt b). (both subclass to t1).

but when I overload the methods show(t a) and show (t1 b) and call it with show(null) it runs fine with the subclass argument version of show.. I thought it might give error here also because t1, t, tt all are subclass to object..

please tell me the reason why it compiled with overloaded method with super and subclass argument but not with sub and sub argument. Thanks in advance.

Here is the code:
---------------------------------------------------------
import java.io.*;
abstract class t1
{
abstract void show();
}

class tt extends t1
{
void show(){}
}


public class t extends t1
{
void show(){}


void show(t1 t) //super
{
System.out.println("t1");
}

void show(tt t) // sub2
{
System.out.println("tt");
}

public static void main(String ar[])
{
new t().show(null);
}
}
// this is compiled--------------------------------------------



---------------------------------------------------------
import java.io.*;
abstract class t1
{
abstract void show();
}

class tt extends t1
{
void show(){}
}


public class t extends t1
{
void show(){}


void show(t t) // sub1
{
System.out.println("t");
}

void show(tt t) // sub2
{
System.out.println("tt");
}

public static void main(String ar[])
{
new t().show(null);
}
}
// this didn't compile--------------------------------------------

Regards
Swati
 
Patricia Samuel
Ranch Hand
Posts: 300
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Swati,

When you call a overloaded method like this show(null), it searches for the most relevant type in the hierarchy. In your case t and tt both are subclass of t1, hence compiler could not decide which one to call.

Whereas in the other scenario you are having super class and subclass mixture, hence it calls subclass overloaded method.



Its just a pseudo code. If you try to simulate this thing you will get answer "String" because String is subclass of Object and hence it can resolved at runtime
 
swati aole
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Patricia for finding time to resolve my query.

Warm Regards
Swati
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

Please use code tags when you post source code.
 
Vinay Dinakar
Greenhorn
Posts: 17
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic