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

Posted on 2014-07-19
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 26

    Accepted Solution

    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

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    sumHeights  challenge 17 52
    Fibonacci challenge 11 62
    Modeling a class in java 5 24
    Running Jira on Raspberry PI 2? 3 50
    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
    Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
    This video teaches viewers about errors in exception handling.

    746 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

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now