-1

everyone! I have two methods which are overloads in the same class.

If I run the below code, I got the error "The method is ambiguous for the type FruitList"

I can't do this:

sample.getFruit((Fruit)null);

nor this:

sample.getFruit((String)null);

I cannot change sample.getFruit(null);

How can I solve this problem??

sample = new FruitList(null);

sample.getFruit(null);------> error
public class FruitList{

        private Fruit head;
        
        public FruitList(Fruit head){
                this.head = head;
        }
       
        public void getFruit(Fruit object){
        }

        public Fruit getFruit(String name){
        }


}

public class Fruit{

        private int amount;
        private String name;

        public Fruit(int amount, String name){
               this.amount = amount;
               this.name = name;
        }


}
anacron
  • 6,443
  • 2
  • 26
  • 31
  • 1
    `sample.getFruit((Game)null)` or `sample.getFruit((String)null)` – Eran Jun 03 '21 at 06:30
  • 1
    ... or do not call a method `getXZY(...)` if it does not return anything... – Turing85 Jun 03 '21 at 06:31
  • 3
    As well as the answers that show you how to convince the compiler to call the method you want, I'd strongly urge you to change the methods. It's very unusual for a method prefixed with `get` not to return something. Usually overloading is used for methods that fundamentally do the same thing, and just express their inputs differently - it looks like that's not going to be the case here. – Jon Skeet Jun 03 '21 at 06:32
  • 2
    For the record, the problem you are experiencing *actually* has nothing to do with the `void` return type. – Stephen C Jun 03 '21 at 06:44
  • Does this answer your question? [Method Overloading for null argument](https://stackoverflow.com/questions/5229809/method-overloading-for-null-argument) – Progman Jun 03 '21 at 09:34

2 Answers2

2

You need to help the compiler a bit in this case. Due to null being a valid value for both Game and String you need to instruct the compiler which of the two methods you mean.

So either

sample.getFruit((Game) null);

Or

sample.getFruit((String) null);
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
  • Thank you for your quick response! Do you have another solution without using (Game) or (String)?? –  Jun 03 '21 at 08:11
  • 1
    Only other way I can think of is to use an intermediate variable. `Game game = null; sample.getFruit(game);` – Jeroen Steenbeeke Jun 03 '21 at 08:17
1

As Game and String input variable both can be replaced with null. Compiler can't decide which method it has to call.

So you can explicitly tell compiler, which method it has to call, by manual type casting to variable as below:

sample.getFruit((Game) null);

or

sample.getFruit((String) null);
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
  • Thank you for your quick response! Do you have another solution without using (Game) or (String)?? –  Jun 03 '21 at 08:11