Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do generic type param shadow reference types? (java)

Let's say we have the following scenario:

public class SomeClass {

}

And now we have a generic class with type parameter SomeClass instead of T.

public class GenericClass <SomeClass> {
    List<SomeClass> list;

    public GenericClass() {
         list = new ArrayList<>();
    }

    public void add(SomeClass obj) {
         list.add(obj);
    }
}

Will the type parameter SomeClass shadow the reference datatype SomeClass in the whole GenericClass?

like image 474
hicksi Avatar asked Aug 11 '26 19:08

hicksi


2 Answers

Yes. That's a name shadow in this context. You can still disambiguate with the fully qualified class name (as long you as you use a package, as you should). Also, this is a good argument for using conventional short type names for your generic types.

like image 135
Elliott Frisch Avatar answered Aug 14 '26 09:08

Elliott Frisch


In a word - yes, it will shadow SomeClass. You could still use the fully qualified class name (e.g., com.exmaple.SomeClass) to reference it, though.

like image 26
Mureinik Avatar answered Aug 14 '26 07:08

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!