Practice mode Java

Inside a generic class Box<T>, which statement is illegal?

Correct answer B. T item = new T();

Explanation

Because of erasure, the actual type T is unknown at run time, so the compiler cannot generate a constructor call and new T() is a compile-time error. Declaring variables of type T, T[] or List is perfectly legal. A common workaround is to accept a Supplier or a Class and create objects through it.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.