Method has the same erasure as another method on a type - part 2

I am completely getting this question Method has the same erasure as another method on the type and the answer is. Please help me understand below?

Don't try to internalize why the below code snippet is giving a compiler error?

Code 1: Compiles Thin

class Parent {
    public void set(Collection<Integer> c) { }
}

class Child extends Parent {
    public void set(Collection<Integer> c) {}
}

      

Code 2: Compiler error with set

Child class.

class Parent {
    public void set(Collection<?> c) { }
}

class Child extends Parent {
    public void set(Collection<Integer> c) {}
}

      

Compiler error

Clash name: set of methods (Collection) of type Child has the same erasure as set (Collection) of type Parent, but does not override it

+3


source to share


2 answers


Because your code in the first example overrides the method from the parent, you end up with one set method for the child:

 public void set(Collection<Integer> c) {}

      

This is obviously good.

In your second example, you are not overriding the supertype method (since the over-riding method is not a sub-signature of the method you are trying to override). Therefore, it must be possible for both methods to exist in the child type.



//from parent:
public void set(Collection<?> c)

//from child:
public void set(Collection<Integer> c)

      

That after erasing the type is impossible:

//from parent:
public void set(Collection c)

//from child:
public void set(Collection c)

      

+1


source


Java uses type erasure. So after type erasure these two methods look the same, however the methods do not override each other, so you end up with two different methods that have the same signature - that's what gives the collision name. This is not valid because it is not known at runtime which one should be used.

If you want to override the method, you can use the wildcard helper method like this:



class Parent {
    public void set(Collection<?> c) { }
}

class Child extends Parent {
    public void set(Collection<?> c) {
        setHelper(c);
    }

    public <T> void setHelper(Collection<T> c) {
        // use T instead of Integer in body of code
    }
}

      

Note: This code will work if you pass it a collection containing integers, however, this code will also work for a collection containing any type but not limited to integers (not checked).

0


source







All Articles