简体   繁体   中英

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

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?

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<?> .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM