Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


How do you declare a generic class in Java that can hold any type of Number?

  1. class GenericClass<T extends Number> {}

  2. class GenericClass<Number> {}

  3. class GenericClass<?> {}

  4. class GenericClass<T> {}

The correct answer is: class GenericClass<T extends Number> {}

A generic class is a class that can work with different types of data. In Java, you can declare a generic class by using the syntax <T> after the class name. To specify that the generic type can hold any type of Number, you can use the keyword "extends" followed by the Number class. This will ensure that the generic class can only hold Number objects and its subclasses. Option B is incorrect because it does not specify the type of Number that the generic class can hold. It also does not use the "extends" keyword to restrict the generic type to Number objects. Option C is incorrect because the wildcard "?" does not specify any type, so it cannot ensure that the generic class can only hold Number objects. Option D is incorrect because it does not specify the type of Number that the generic class can hold. Without the "extends" keyword, the generic class can hold any