2

The following Java code cannot be compiled with an error: Names conflict.

class Test {

    public void f(Class<?> c) {
    }

    public void f(Class c) {
    }
}

Is there any difference between void f(Class c) and void f(Class<?> c) in Java?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
xmllmx
  • 39,765
  • 26
  • 162
  • 323

2 Answers2

4

Declared in the same class, they are override-equivalent and will cause a compilation error.

From the Java Language Specification

It is a compile-time error to declare two methods with override-equivalent signatures in a class.

where

Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.

and

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1, or
  • the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

The bolded case is the problem here.

The erasure of Class<?> is Class.

Is there any difference between void f(Class c) and void f(Class c) in Java?

From a caller's perspective, no. Within the body of the method, yes. In the first case, the parameter has the raw type Class. In the second case, the parameter has the parameterized type Class<?>.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

Actually ? is a wild-card which can be used with parametrized classes/interfaces. For example Collection<Object> is a generic collection which contains items of type Object whereas Collection<?> is a super type of all types of collections.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95