0

given:

static class ClassA {
    static <V> ClassA create( List<V> things ) {
        //do something with things
        return new ClassA();
    }
}

static class ClassB extends ClassA {
    //note: using <V> is fine, but <V extends Number> gives an error
    static <V extends Number> ClassB create(List<V> numbers) {
        //do something with numbers
        return new ClassB();
    }
}

I am getting the error:

'create(List)' in 'ClassB' clashes with 'create(List)' in 'ClassA'; both methods have same erasure, yet neither hides the other

Easy way around this problem is to just name the methods differently, but I want to better understand why this is a problem (and if there are workarounds).

From my understanding of static methods, the method to call is picked based on the static type of the object. so ClassA foo = new ClassB(); foo.create(null); would make a call to ClassA.create(null). And of course, there shouldn't be a problem with picking the right method when using the class name directly: ClassB.create or ClassA.create.

My guess is that it would have a problem with ClassB.create(new ArrayList<String>()). Though at compile time, it would still be possible to determine that ClassA.create could (should(?)) be called.

Aarjav
  • 1,334
  • 11
  • 22
  • Static methods cannot be overridden. – xiaofeng.li Nov 01 '17 at 23:13
  • Which method should this call: `ClassB.create(new ArrayList())` – shmosel Nov 01 '17 at 23:14
  • @xiaofeng.li I am not trying to override them as such, otherwise i could use ` for ClassB` which compiles and works. – Aarjav Nov 01 '17 at 23:16
  • @shmosel `ClassB`'s create, mainly because of the explicit `ClassB`. – Aarjav Nov 01 '17 at 23:17
  • `ClassB` effectively declares both methods, since neither can hide the other. – shmosel Nov 01 '17 at 23:19
  • the compiler puts a 'copy' of the method in `ClassB`? that doesn't sound right, private static fields used in `ClassA` would no longer be accessible by `ClassB` if that were the case – Aarjav Nov 01 '17 at 23:27
  • Perhaps this [question](https://stackoverflow.com/questions/18998280/name-clash-compile-error-when-compiled-in-java-7-but-works-fine-in-java-5) can give you the answer. – xiaofeng.li Nov 01 '17 at 23:28
  • I think the problem is that Java allows static methods to be accessed via an object and not just by the class name itself. It's not recommended but it's allowed. `ClassB obj = new ClassB(); obj.create(new List() );` and the compiler can't decide which you mean. Not sure but that's the only thing that comes to mind. – markspace Nov 01 '17 at 23:42
  • 1
    incase of `obj.create` it is chosen based on the static type of `obj`, which is why `ClassA obj = null; obj.create(null)` would not throw a NullPointerException. – Aarjav Nov 01 '17 at 23:46

0 Answers0