I'm beginner at Generic in Java and I'm following a course about this concept. the instructor of this course explain about these code this way:
Codes:
public class Instructor extends User { // --- }
--
public class Utils {
public static void printUsers(GenericList<User> users){
// ---
}
}
--
public class Test {
public static void main(String[] args) {
var users = new GenericList<Instructor>();
Utils.printUsers(instructors);
}
}
his explanations:
in the main method , we get compilation error because a GenericList of
Instructor
is not a subtype of GenericList ofUser
. I meanGenericList<Instructor>
does not extend and inheritGenericList<User>
.why is that? we looked at bytecode representation of this GenericList class. as I'd show you earlier this GenericList internally maintains a list of
Object
s no matter what we pass as a type parameter.whether we passed the
User
Class orInstructor
Class, we only have a singleGenericList
in our project and this class is not a subtype of itself. that is the reason why a GenericList ofInstructor
is not a subtype of GenericList ofUser
. because we're dealing with a single class.
Now; I'm totally confused. very very confused!
Why does he say we have only a single class?
GenericList<Instructor>
andGenericList<User>
are two class, although they have same byte code. (because both of them maintain list of Object and compiler will replace everyT
withObject
)If we only have a single GenericList in our project and this class is not a subtype of itself, then there is no different between instance of
GenericList<Instructor>
and instance ofGenericList<User>
and they are both belong to the same class.
Why did I get such a result? because according to the teacher, we only just have a single class then why printUsers
method does not accept an instance of GenericList as an argument?
and at the end , I don't understand anything about this paragraph at all :
whether we passed the
User
Class orInstructor
Class, we only have a singleGenericList
in our project and this class is not a subtype of itself. that is the reason why a GenericList ofInstructor
is not a subtype of GenericList ofUser
. because we're dealing with a single class.
can anyone help me to understand these explanation? Thank You.