Class<? extends A> classB
vs
A classB
What's the difference here? Is it just that the first one is an instance of the Class
and the second is an instance of the actual Object
?
Class<? extends A> classB
vs
A classB
What's the difference here? Is it just that the first one is an instance of the Class
and the second is an instance of the actual Object
?
Class<? extends A>
and A
are completely two different types.
A variable of type Class<? extends A>
contains information about a class. The class can be A
or any class that extends A
, depending on the value of the variable. Things you can do with a Class<? extends A>
variable includes: getting all the field names declared in the class, getting all the method names declared in the class, getting the super class of the class, and many others.
A variable of type A
refers to an instance of A
. If you declared a non-static method called foo
in the class A
, then you can call foo
directly with this variable:
yourVariable.foo();
You can't directly do this if yourVariable
is of type Class<? extends A>
.
See the difference here? Class<? extends A>
is kind of like a "metatype" whose instances contain information about a type (this type can be A
or a subclass of A
), whereas A
is the type you declared. An instance of A
represents whatever thing the class is modelled after. An instance of a Bicycle
class represents a bicycle. It may have methods like pedal
and turn
and fields like durability
. An instance of Class<? extends Bicycle>
will tell you things like: in the Bicycle class, there is a field called durability
, and there is a method called pedal
.
Basically, "meta" is the keyword here. Class
is a class that represents a class.
The first
Class<? extends A> classB
defines a member which has the type Class
which represent classes and interfaces in a running Java application Class
So you can write
classB = A.class;
classB = AExtended.class;
The second one
A classB
defines a member of type A
so you can write
classB = new A();
classB = new AExtended();