Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 8.9 Inheritance Exercises

(Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.)

Exercises Exercises

Fill in the blank.

Fill in the blanks in each of the following sentences:
1.
A method that lacks a body is an method.
2.
An is like a class except that it contains only instance methods, no instance variables.
3.
Two ways for a class to inherit something in Java is to a class and an interface.
4.
Instance variables and instance methods that are declared or are inherited and usable by the subclasses.
5.
An object can refer to itself by using the keyword.
6.
If a GUI class intends to handle ActionEvent s, it must implement the interface.
7.
A method is one that does different things depending upon the object that invokes it.

8. Java Concept Matching.

9. Language Hierarchy.

Create a hierarchy to represent the following situation. There are lots of languages in the world. English, French, Chinese, and Korean are examples of natural languages. Java, C, and C++ are examples of formal languages. French and Italian are considered romance languages, while Greek and Latin are considered classical languages. Note: Indenting a language puts it on a lower level. Languages on the same level should be in alphabetical order, but languages that don’t have children should precede languages that do.

10. JButton Methods.

Look up the documentation for the JButton class on Sun’s Web site: http://java.sun.com/j2se/1.5.0/docs/api/. List the names of all the methods that would be inherited by the ToggleButton subclass that we defined in this chapter.

11. Toggle Button toString().

Design and write a toString() method for the ToggleButton class defined in this chapter. The toString() method should return the ToggleButton’s current label.

12. Employee Class Hierarchy.

Design a class hierarchy rooted in the class Employee that includes subclasses for HourlyEmployee and SalaryEmployee. The attributes shared in common by these classes include the name, and job title of the employee, plus the accessor and mutator methods needed by those attributes. The salaried employees need an attribute for weekly salary, and the corresponding methods for accessing and changing this variable. The hourly employees should have a pay rate and an hours worked variable. There should be an abstract method called calculateWeeklyPay(), defined abstractly in the superclass and implemented in the subclasses. The salaried worker’s pay is just the weekly salary. Pay for an hourly employee is simply hours worked times pay rate.

13. Write IntegerField.

Design and write a subclass of JTextField called IntegerField that is used for inputting integers but behaves in all other respects like a JTextField. Give the subclass a public method called getInteger().

14. Increasing Shift Cipher.

Implement a method that uses the following variation of the Caesar cipher. The method should take two parameters, a String and an int N. The result should be a String in which the first letter is shifted by N, the second by \(N+1\text{,}\) the third by \(N+2\text{,}\) and so on. For example, given the string “Hello,” and an initial shift of 1, your method should return “Igopt.” Write a method that converts its String parameter so that letters are written in blocks five characters long.

15. Substitution Cipher.

Design and implement a Cipher subclass to implement the following substitution cipher: Each letter in the alphabet is replaced with a letter from the opposite end of the alphabet: a is replaced with z, b with y, and so forth.

16. Alphabet Class.

One way to design a substitution alphabet for a cipher is to use a keyword to construct the alphabet. For example, suppose the keyword is “zebra.” You place the keyword at the beginning of the alphabet, and then fill out the other 21 slots with remaining letters, giving the following alphabet:
Cipher alphabet:   zebracdfghijklmnopqstuvwxy
Plain alphabet:    abcdefghijklmnopqrstuvwxyz
Design and implement an Alphabet class for constructing these kinds of substitution alphabets. It should have a single public method that takes a keyword String as an argument and returns an alphabet string. Note that an alphabet cannot contain duplicate letters, so repeated letters in a keyword like “xylophone” would have to be removed.

17. Alphabet Cipher.

Design and write a Cipher subclass for a substitution cipher that uses an alphabet from the Alphabet class created in the previous exercise. Challenge: Find a partner and concoct your own encryption scheme. Then work separately with one partner writing encode() and the other writing decode(). Test to see that a message can be encoded and then decoded to yield the original message.

18. Multiplication Game.

Design a TwoPlayerGame subclass called MultiplicationGame. The rules of this game are that the game generates a random multiplication problem using numbers between 1 and 10, and the players, taking turns, try to provide the answer to the problem. The game ends when a wrong answer is given. The winner is the player who did not give a wrong answer.

19. Multiplication Player.

Design a class called MultiplicationPlayer that plays the multiplication game described in the previous exercise. This class should implement the IPlayer interface.

20. Rock Paper Scissors Game.

Design a TwoPlayerGame subclass called RockPaperScissors. The rules of this game are that each player, at the same time, picks either a rock, a paper, or a scissors. For each round, the rock beats the scissors, the scissors beats the paper, and the paper beats the rock. Ties are allowed. The game is won in a best out of three fashion when one of the players wins two rounds.

21. Rock Paper Scissors Player.

Design a class called RockPaperScissorsPlayer that plays the the game described in the previous exercise. This class should implement the IPlayer interface.

22. Animal Hierarchy.

Given the classes with the following headers
public class Animal ...
public class DomesticAnimal extends Animal ...
public class FarmAnimal extends DomesticAnimal...
public class HousePet extends DomesticAnimal...
public class Cow extends FarmAnimal ...
public class Goat extends FarmAnimal ...
public class DairyCow extends Cow ...
draw a UML class diagram representing the hierarchy created by these declarations.

24. Tracing SomeFrame.

The JFrame that follows contains a semantic error in its SomeFrame() constructor. The error will cause the actionPerformed() method never to display “Clicked” even though the user clicks the button in the JFrame. Why? (Hint: Think scope!)
public class SomeFrame extends JFrame
                implements ActionListener
{
  // Declare instance variables
  private JButton button;
  public JFrame()
  {
    // Instantiate the instance variable
    JButton button = new JButton("Click me");
    add(button);
    button.addActionListener(this);
  } // init()
  public void actionPerformed(ActionEvent e)
  {
    if (e.getSource() == button)
      System.out.println("Clicked");
  } // actionPerformed()
} // SomeFrame

25. Trace SomeFrame2.

What would be output by the following program?
public class SomeFrame2 extends JFrame
{
  // Declare instance variables
  private JButton button;
  private JTextField field;
  public SomeFrame()
  {
    // Instantiate instance variables
    button = new JButton("Click me");
    add(button);
    field = new JTextField("Field me");
    add(field);
    System.out.println(field.getText() + button.getText());
  } // init()
  public static void main(String[] args) {
    SomeFrame2 frame = new SomeFrame2();
    frame.setSize(400,400);
    frame.setVisible(true);
  }
} // SomeFrame2

26. GUI Parts and their String Representations.

Design and implement a GUI that has a JButton, a JTextField, and a JLabel and then uses the toString() method to display each object’s string representation.

27. Toggle Doctor.

The JButton class inherits a setText(String s) from its AbstractButton() superclass. Using that method, design and implement a GUI that has a single button labeled initially, “The Doctor is out.” Each time the button is clicked, it should toggle its label to, “The Doctor is in.” and vice versa.
You have attempted of activities on this page.