-1

As per my readings/understandings:-

Every time JVM creates an object, it also creates a java.lang.Class object that describes the type of the object. All instances of the same class share the same Class object.

Class<SomeClass> is a way to represent this object, which is of type Class and was created when any object of type SomeClass class was created(as per above definition) and also, is associated with SomeClass class.

But when I read below StackOverflow thread, regarding Class<?>:-

What does Class<?> mean in Java?

it is said in the very first answer that by writing Class<?>, we're declaring a Class object which can be of any type. I am so confused, wouldn't this object be of type Class regardless of what ? is, since its an object of class Class?

I don't understand what 'generic' is. If you have to use that term in your answer, I'd really appreciate if you can simultaneously explain that too. Thanks.

Vyom
  • 1
  • 2
    You probably want to start [here](https://docs.oracle.com/javase/tutorial/java/generics/). IMO this question is too broad. – Mena Aug 29 '17 at 14:19
  • If you don't want to deal with generics, you don't have to worry about the unknown type ( >). – tomas Aug 29 '17 at 14:26

1 Answers1

0

it is said in the very first answer that by writing Class<?>, we're declaring a Class object which can be of any type. I am so confused, wouldn't this object be of type Class regardless of what ? is, since its an object of class Class?

No. When you use Class<?>, you force the use of a parametrizable class. For example, you can use a List<>, because List is parametrizable: List<String> for example. You can't use Dog.

I don't understand what 'generic' is. If you have to use that term in your answer, I'd really appreciate if you can simultaneously explain that too

As per the documentation:

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

The easiest way to understand them is probably to look at the Lists classes. When you use:

List<String> list = new ArrayList<>();

You're specifying a type linked to your List. This type can then be used in your functions or implementations:

Imagine this function in the ArrayList class:

public T get(int index) {
    return this.get(index);
}

This function will return a String object, because I declared it as a List<String>! So I don't have to manipulate a list of objects, then cast it myself. I defined the contents of the list in the declaration of my list.

Turtle
  • 1,626
  • 16
  • 26