go to previous page   go to home page   go to next page

Answer:


Arrays of 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 tells the compiler what a variable is expected to refer to when the variable itself is not specific enough.


QUESTION 16:

Is the following OK?

Object obj;
obj = "Yertle" ;
 
((YouthBirthday)obj).greeting();

go to previous page   go to home page   go to next page