CS 1054: Lab 11

Lab meeting 11: Inheritance and Polymorphism 

This exercise will introduce you to inheritance and polymorphism. Class behavior can be extended through inheritance. Polymorphism means that invoking the same method on the same reference variable will invoke different methods depending upon the type of the object being referred to. Or in other words, the same message can evoke different behavior depending upon the class to which the receiver belongs.

Tasks

  1. To begin this lab, open BlueJ and then start a new project. Name it "lab11". Note: Please follow the next instructions carefully. Create four new classes in your project called NameDemo, Name, HispanicName and EnglishName. Do not open these classes yet. Download the files NameDemo.java, Name.java, HispanicName.java and EnglishName.java from the course web page using the following location: http://courses.cs.vt.edu/~cs1054/fall2003/labs/lab11/ in the same directory where you have your project stored.
  2. Compile the classes and invoke the main method of the NameDemo class. Observe the values that are printed.
  3. Some of the methods defined in the classes HispanicName and EnglishName are commented out. Remove the comments (the two lines in each file are marked with "step 3"). Compile and run the program and notice how the values have changed. Which methods were executed in step 2, and which methods are being executed here? Identify them by class and name.
  4. Comment out the block of output statements marked with "steps 2 & 3" in the NameDemo class, and uncomment the block marked "step 4". Attempt to compile the program. What line (A or B) does the compiler complain about? Explain why.
  5. Comment out the block used in step 4. Uncomment the blocks marked with "step 5". Replace the question marks on "step 5, line A" with the appropriate type. Compile and run and verify that it works. What type did you end up using? Explain why this is the correct type.
  6. Write down your answers to steps 3, 4 and 5 above on a sheet of paper and show them to the GTA.

© Mir Farooq Ali 2003.