Hello Friend= new Hello("LOL");
Now you have variable named Friend
of compile-time type Hello
referring to an object of runtime type Hello
Object myObj = Friend;
Now you have a variable named myObj
of compile-time type Object
also referring to the same object of runtime type Hello
. This is allowed because every Hello
is also an Object
.
Hello myFriend = myObj; // What's wrong with this line ?
This fails during compilation because myObj
has the compile-time type Object
and you're trying to assign it to a new variable of compile-time type Hello
. And most Object
s are not Hello
s. The compiler doesn't try to figure out whether this particular one is, because that is not possible in general.
But you can force the compiler to do it anyway by assuring you that this particular Object
s is in fact a Hello
:
Hello myFriend = (Hello) myObj;
This is called casting.