Java <T> Generics: new Box<String>("Hello"); vs. new Box<MyClass>("Hello");

Posted on 2014-07-19
Medium Priority
Last Modified: 2014-07-19
I have a simple class that boxes a generic type:
public class Box<T> {
    private T t;
    public Box(T t) { this.t = t; }
    public void set(T t) { this.t = t; }
    public T get() { return t; }
    public void Write()

Open in new window

Then I create a simple class of my own:
public final class MyClass {
	private String s;
	public MyClass(String s) {
		this.s = s;

    public String get() { return s; }

Open in new window

and some code to test it:
public class TestBox {

	public static void main(String[] args) {
		Box<Integer> integerBox = new Box<Integer>(7);

		Box<String> stringBox = new Box<String>("Hello");

		Box<MyClass> myClassBox = new Box<MyClass>("Hello");


Open in new window

Why does this test work for Integer and String, but it doesn't work for MyClass?  It says "The constructor Box<MyClass>(String) is undefined."

Where is the constructor Box<String>(String) defined?
Where is the constructor Box<Integer>(Integer) defined?
Question by:deleyd
1 Comment
LVL 28

Accepted Solution

dpearson earned 2000 total points
ID: 40206409
You're trying to initialize Box<MyClass> with a String (value "Hello") not an instance of MyClass.

Try this instead:
Box<MyClass> myClassBox = new Box<MyClass>(new MyClass("Hello"));


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month15 days, 12 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question