rashid
rashid

Reputation: 264

How does method over riding work in case where method signature remains same but generic parameters differ?

I was trying following example:

class BaseClass {
    public void methodA(Class<?> cl) {
        System.out.println("Base.methodA()");
    }
}

class SubClass extends BaseClass {
    public void methodA(Class cl) {
        System.out.println("Sub.methodA()");
    }
}

public class OverrideEx {

    public static void main(String[] args) {
        BaseClass b = new BaseClass();
        BaseClass s = new SubClass();

        b.methodA(Class.class);
        s.methodA(Class.class);
    }
}

Output: Base.methodA() Sub.methodA()

But if I change over riding method argument other way around as follows:

class BaseClass {
    public void methodA(Class cl) {
        System.out.println("Base.methodA()");
    }
}

class SubClass extends BaseClass {
    public void methodA(Class<?> cl) {
        System.out.println("Sub.methodA()");
    }
}

public class OverrideEx {

    public static void main(String[] args) {
        BaseClass b = new BaseClass();
        BaseClass s = new SubClass();

        b.methodA(Class.class);
        s.methodA(Class.class);
    }
}

I get compilation error. It says "Name clash: The method methodA(Class) of type SubClass has the same erasure as methodA(Class) of type BaseClass but does not override it".

Why is that?

Upvotes: 2

Views: 134

Answers (2)

Ben Schulz
Ben Schulz

Reputation: 6181

The parameterized type Class<?> is a subtype of the raw type Class4.10.2).

Thus for any x the call s.methodA(x) in the first example would also be valid if rewritten:

((BaseClass)s).methodA(x)

This is not true for the second example.

Imagine x being of type Class which is not a subtype of Class<?>. That call would be illegal because the argument's type is not a subtype of the formal parameter's type.

This means that methodA of SubClass does not override methodA of BaseClass.

Upvotes: 2

Jerome
Jerome

Reputation: 4572

According to the JLS, you can override a method if (amongst other things): The signature of m1 is a subsignature (§8.4.2) of the signature of m2.

That means that ( JLS again ):
- m2 has the same signature as m1, or
- the signature of m1 is the same as the erasure of the signature of m2.

In your attempt to override methodA, you have the same type erasure but you don't have the same signature. In this very chapter of the jls, there's a discussion on the matter you are describing.

Upvotes: 0

Related Questions