LearnFrenzy
Sign in Take a free test

Generics · Find the Error · Question 1

Error: creating an object with new T() Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
class Factory<T> {
    T create() {
        return new T();
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Factory<StringBuilder>().create());
    }
}
  • A create must be static
  • B T is erased at run time, so new T() is impossible; pass a Supplier<T> (e.g. StringBuilder::new) or a Class<T> Correct
  • C StringBuilder has no constructor
  • D Factory must be abstract
Correct Answer: Option B

javac: "unexpected type – required: class, found: type parameter T".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links