Arrays of Object

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.

Answer:

  • Is a String an Object?
    • Yes
  • Is a Card an Object?
    • Yes
  • Is a Applet an Object?
    • Yes

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 is used to tell the compiler what is "really" in a variable that itself is not specific enough.

QUESTION 16:

Is the following OK?

Object obj;
String str = "Yertle" ;

obj = str;
((YouthBirthday)obj).greeting();