String
an Object
?
Card
an Object
?
Applet
an Object
?
Since every class is a descendant of Object
,
an Object
reference variable can be used with
an object of any class.
For example:
Object obj; String str = "Yertle" ; Double dbl = new Double( 32.0 ); YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); obj = str; obj = dbl; obj = ybd;
Each of the last three statements is correct (although in this program, useless.) It would not be correct if this followed the above statements:
obj.greeting();
It is true that obj
refers to a YouthBirthday
object, which has a greeting()
method.
But the compiler needs to be told this with a type cast.
The following is OK:
((YouthBirthday)obj).greeting();
A typecast is used to tell the compiler what is "really" in a variable that itself is not specific enough.
Is the following OK?
Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting();