joey rohan
joey rohan

Reputation: 3566

Why generic to object type-casting is implicit?

While converting an non-generic class to a generic one, I saw this working :

public class TestException<T>
{
    T t;
    Object getObj(){
        return t;   
    }
}

When I tried to change the return-type from Object to any other say String, I had to type cast it :

String getObj(){
    return (String)t;   
}

Why generic to object type-casting is implicit ? Couldn't find any implementation on java docs.

Upvotes: 0

Views: 139

Answers (4)

dramzy
dramzy

Reputation: 1429

Every instance of every class ISA Object, so you can always cast any reference type value to Object. Only a String object, however, ISA String.

Upvotes: 1

user2717954
user2717954

Reputation: 1902

even if T wasn't generics type it would have worked. try it yourself!

you can always return something as it super type, same goes for generics

Upvotes: 1

Makoto
Makoto

Reputation: 106430

Since your generic type T is unbound, it gets the implicit bound T extends Object. This means that it's fine for it to be returned as an Object.

There's no guarantee that T is a String, so you're forced to cast it (and you run the risk of runtime exceptions if you do and T is not a String).

Upvotes: 5

SLaks
SLaks

Reputation: 887449

Every class inherits Object, so T is guaranteed to be implicitly convertible to Object.

Upvotes: 7

Related Questions