parsecer
parsecer

Reputation: 5176

Overloading a method: both methods have same erasure

I have the following code and it doesn't work: the error both methods have same erasure appears.

public class Foo<V>  {
    public static void main(String[] args)  {
    }

    public void Bar(V value)  {
    }

    public void Bar(Object value)  {
    } 
}

Also I have this code:

public class Foo<V>  {
    public static void main(String[] args)  {
    }

    public void Bar(B value)  {
    }

    public void Bar(A value)  {
    }
}

class A  {
}

class B extends A  {
}

And this works. In the first case V is a child of Object, just like in the second case B is a child of A. Then why the first case results in error, while the second compiles successfully?

EDIT: What should I do to achieve method overloading, without raising an error?

Upvotes: 29

Views: 68443

Answers (2)

Kayaman
Kayaman

Reputation: 73578

V isn't "a child of Object". V is an unbounded generic type that erases to Object, resulting in the error. If the generic type were bounded, such as <V extends Comparable<V>>, it would erase to Comparable and you wouldn't get the error.

Upvotes: 8

Andy Turner
Andy Turner

Reputation: 140534

What should I do to achieve method overloading, without raising an error?

Simple: don't try to overload the method with parameters with the same erasure.

A few options:

  1. Just give the methods different names (i.e. don't try to use overloading)
  2. Add further parameters to one of the overloads, to allow disambiguation (ideally only do this if you actually need those parameters; but there are examples in the Java API where there are junk parameters simply to avoid overloading issues).
  3. Bound the type variable, as suggested by @Kayaman:

    <V extends SomethingOtherThanObject>
    

Upvotes: 36

Related Questions