2

I following definitions of the class.

public class Test2<T extends Test3> {

     private T t ;


     public T foo() {
         Test3 test3 = new Test3();
         t = test3;  // I get compilation error here.**
         return t;
     }

}

class Test3 {

}

I get compilation error at line t=test3, saying "Type mismatch can not convert from Test3 to T; What is wrong?

4
  • Can a child object variable refer to a parent object? Commented Dec 5, 2010 at 14:10
  • 1
    @Hovercraft: no, it cannot, that's precisely the problem (see my answer) Commented Dec 5, 2010 at 14:11
  • 1
    I know that Mark, I wanted the OP to understand it, but I posted as a comment rather than an answer. :( Commented Dec 5, 2010 at 14:13
  • @Hovercraft - +1 to your answer below for trying to use the Socratic method of teaching here and getting answered by another poster. Made me laugh. Commented Dec 5, 2010 at 14:25

4 Answers 4

8

What you're doing is equivalent to this:

Integer n = new Number();

and has nothing to do with generics (note that Integer extends Number). The compiler is indicating you cannot assign a parent type to an instance of a child type, the parent type may not implement all the child type's required methods.

In this case T is the child type of Test3, or Test3 itself. So here, you're trying to assign the parent class (T) to a variable that contains the child class (Test3) and it fails, just like the example above.

Sign up to request clarification or add additional context in comments.

Comments

2

T is a subclass of Test3. As such, unless it is exactly Test3 the assignment will fail since subclasses can be assigned to variables of a superclass type but the reverse is not true.

Comments

1

Can a child object variable refer to a parent object?

Just test it without the generics:

public class Foo {

    public static void main(String args[]) {
        T t = new Test3();
    }
}

class T extends Test3 {
}

class Test3 {
}

edit: nevermind, I initially posted as a comment, then posted as an answer... but was too late! :)

Comments

0

Because it is downcast. T can be any class derived from Test3, if you sure (but why you need T, use always Test3) you can use follow explicit casting:

@SuppressWarnings("unchecked")
t = (T)test3;

2 Comments

I want to return instance of Test3. Is writing method without Generics is only solution?
will it look ugly if I cast like following. @SuppressWarnings("unchecked") t = (T)test3;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.