Skip to main content

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.)

  1. 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 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.

  2. Explain the difference between the following pairs of terms:

    1. Class and interface.

    2. Stub method and abstract method.

    3. Extending a class and instantiating an object.

    4. Defining a method and implementing a method.

    5. A protected method and a public method.

    6. A protected method and a private method.

  3. Draw 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.

  4. 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.

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

  6. 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.

  7. 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().

  8. 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.

  9. Design and implement an GUI that lets the user type a document into a TextArea and then provides the following analysis of the document: the number of words in the document, the number of characters in the document, and the percentage of words that have more than six letters.

  10. 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.

  11. 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.

  12. 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.

  13. 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.

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

  15. 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.

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

  17. 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.

  18. Given the preceding hierarchy of classes, which of the following are legal assignment statements?

    DairyCow dc = new FarmAnimal();
    FarmAnimal fa = new Goat();
    Cow c1 = new DomesticAnimal();
    Cow c2 = new DairyCow();
    DomesticAnimal dom = new HousePet();
    

  19. 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
    
  20. 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
    

  21. 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.

  22. 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.