1

The four methods:

public Class<?> Func(Class<?> cls)  //1
public Class<?> Func(Class cls)  //2
public Class Func(Class<?> cls)  //3
public Class Func(Class cls)  //4

I found that:

1) 4 can override 3
2) 3 can't override 4.
3) But 2 and 4 can override each other.

Why?

This is may not about type conversion, since Class and Class<> can be converted to each other. This is more about why the compiler prevent (2) but allows (1) and (3).

jw_
  • 1,663
  • 18
  • 32
  • 1
    quite unclear, can you share what have you tried for this override? – Vinay Prajapati Oct 18 '19 at 08:03
  • 1
    You shouldn't write 2, 3 and 4 in new code, however. They're using a raw type, [which should **not** be used](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – MC Emperor Oct 18 '19 at 09:29
  • @Vinay Prajapati I'm just building the code to find out the usage of question mark during inheritance. – jw_ Oct 19 '19 at 01:05

1 Answers1

0

Reasons -
1 - Class means, any kind of Class object, i.e Class<?>.

2 - Function having Class<?> parameter cannot edit the object of Class<?> type, but a function having Class parameter can.

for example -

// function 1
void m(List<?> list){
    list.add(3);
}
// function 2
void m(List<?> list){
    list.get(0);
}

function 1 would not compile because it has a parameter List<?>, which means any list can be sent as parameter, but it cannot be editted, because one might send a List<String> and try to add an Integer to that list.

3 - A method can be overriden if the return type is the same or a subtype, and Class<?> and Class are same as return types as they both are returning Class objects, and any Class object can be typecasted to Class<?> or vice-versa

Nikunj Gupta
  • 126
  • 2
  • 8
  • Does Class means Class? I think Class is more close to Class>. You can check out that "public Class Func(Class cls)" can't override any of them. – jw_ Oct 19 '19 at 01:03
  • @jw_ yes I that makes sense, as `Class` would only except `Class` but `Class>` can except any kind of `Class` object – Nikunj Gupta Oct 20 '19 at 08:11