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

vaps
  • 57
  • 5
  • Could you extend your examples to provide a little more context? – Yunnosch Aug 10 '18 at 05:27
  • 3
    Possible duplicate of [What does the question mark in Java generics' type parameter mean?](https://stackoverflow.com/questions/3009745/what-does-the-question-mark-in-java-generics-type-parameter-mean) – Phil Aug 10 '18 at 05:29
  • 1
    @Phil the accepted answer there states "A class/interface that extends `A`." When my question is asking what the difference is when that answer can be said about `A classB` as well. `classB` can also be "A class/interface that extends `A`." – vaps Aug 10 '18 at 05:45
  • @Phil That is definitely not a duplicate of this question – Mark Rotteveel Aug 10 '18 at 13:07
  • Alright. There's a reason it says "possible". – Phil Aug 10 '18 at 23:48

2 Answers2

3

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

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();
Alexander Egger
  • 5,132
  • 1
  • 28
  • 42
  • This is good too. It shows how you cannot instantiate a class of type `Class`. You just don't go into detail about what you can do with type `Class` vs an actual instance of that class. – vaps Aug 10 '18 at 19:36