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.)
-
Fill in the blanks in each of the following sentences:
- A method that lacks a body is an
__________
method. - An
__________
is like a class except that it contains only instance methods, no instance variables. - Two ways for a class to inherit something in Java is to
__________
a class and__________
an interface. - Instance variables and instance methods that are declared
__________
or__________
are inherited by the subclasses. - An object can refer to itself by using the
__________
keyword. - If a GUI class intends to handle
ActionEvent
s, it must implement the__________
interface. - A
__________
method is one that does different things depending upon the object that invokes it.
-
Explain the difference between the following pairs of terms:
- Class and interface.
- Stub method and abstract method.
- Extending a class and instantiating an object.
- Defining a method and implementing a method.
- A
protected
method and apublic
method. - A
protected
method and aprivate
method.
- 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.
- 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 theToggleButton
subclass that we defined in this chapter. - Design and write a
toString()
method for theToggleButton
class defined in this chapter. ThetoString()
method should return theToggleButton
’s current label. - Design a class hierarchy rooted in the class
Employee
that includes subclasses forHourlyEmployee
andSalaryEmployee
. 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 calledcalculateWeeklyPay()
, 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. - Design and write a subclass of
JTextField
calledIntegerField
that is used for inputting integers but behaves in all other respects like aJTextField
. Give the subclass a public method calledgetInteger()
. - Implement a method that uses the following variation of the Caesar cipher. The method should take two parameters, a
String
and anint
N. The result should be aString
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 itsString
parameter so that letters are written in blocks five characters long. - 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. - 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. - 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:Design and implement an
Cipher alphabet: zebracdfghijklmnopqstuvwxy Plain alphabet: abcdefghijklmnopqrstuvwxyz
Alphabet
class for constructing these kinds of substitution alphabets. It should have a single public method that takes a keywordString
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. - Design and write a
Cipher
subclass for a substitution cipher that uses an alphabet from theAlphabet
class created in the previous exercise. Challenge: Find a partner and concoct your own encryption scheme. Then work separately with one partner writingencode()
and the other writingdecode()
. Test to see that a message can be encoded and then decoded to yield the original message. - Design a
TwoPlayerGame
subclass calledMultiplicationGame
. 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. - Design a class called
MultiplicationPlayer
that plays the multiplication game described in the previous exercise. This class should implement theIPlayer
interface. - Design a
TwoPlayerGame
subclass calledRockPaperScissors
. 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. - Design a class called
RockPaperScissorsPlayer
that plays the the game described in the previous exercise. This class should implement theIPlayer
interface. - Given the classes with the following headersdraw a UML class diagram representing the hierarchy created by these declarations.
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 ...
- 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();
-
The JFrame that follows contains a semantic error in its
SomeFrame()
constructor. The error will cause theactionPerformed()
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
- 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
- Design and implement a GUI that has a
JButton
, aJTextField
, and aJLabel
and then uses thetoString()
method to display each object’s string representation. - The
JButton
class inherits asetText(String s)
from itsAbstractButton()
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.