Lab 10: Interfaces

In this lab, you will work with interfaces.

Objectives:

Part 1: Implementing an Interface

In this part, you will write a class that implements an interface -- the interface specifies the required behavior for filtering lists of files.

Steps:

  1. Use Windows Explorer to examine the contents of the {Lab Installation Directory}/stuff directory -- note that it contains a mixture of .txt and other files.

    If your computer has the standard lab setup on Windows XP, that directory is:

    c:\javaclasss\stuff         
             

    If your computer has the standard lab setup on Windows Vista or later, the directory is:

    c:\Users\username\javaclass\stuff         
             

  2. In Eclipse, create a new Java project named Lab10.

  3. Look in the JavaDoc for the java.io.File class. The File class represents an file or directory on a disk and provides methods to let you work with the file or directory.

    Note that the class has a constructor that accepts a pathname String (which could be for a directory) and that it defines overloaded listFiles methods that return an array containing entries representing files in the directory.

    One of the listFiles methods accepts an argument of type FileFilter, which is an interface -- classes that implement this interface can filter the returned list of files.

    Create a class named MyFileFilter in the part1 package that implements the FileFilter interface. This class does not need a main method, but ensure that the Inherited abstract methods checkbox is selected.

    Hint: In the New Class wizard, you can add interfaces by pressing the Add button next to the Interfaces entry field and then starting to type "FileFil".

  4. To implement FileFilter, your class must provide a method named accept that accepts a File object and returns true if the file should be listed, false if not.

    Complete this method so that it returns true for files whose path ends in .txt and false otherwise. Hint: look at the File class's getPath method and the String class's endsWith method. Here's some code to help you get started:

    String path = arg0.getPath();         
    boolean ok = path.endsWith(".txt");         
             

  5. Create another class named ListFiles in the part1 package. This class should have a main method.

  6. Complete main so that it:

    1. Creates a File object using the File class's one-argument constructor that accepts a String pathname. Set the pathname to {Lab Installation Directory}/stuff, which is the directory containing a mixture of text and other files.

    2. Creates an instance of the MyFileFilter class using the no-argument constructor.

    3. Calls the File object's listFiles method, passing the MyFileFilter object reference. Note that this method returns an array of File objects -- each entry in the array represents a file in the directory. If your filter is working properly, the array should only contain File objects for files whose name ends in .txt.

    4. Has a for loop that traverses the returned array of File objects, printing each File object to the console.

  7. Run and test your program -- do you see a listing of only file names that end in .txt?

Part 2: Writing an Interface

In this part, you will write an interface. The company that imports automobiles has decided to expand to import other goods that require a duty payment. You will thus write an interface that describes the behavior required by all dutiable items.

Steps:

  1. Use the Eclipse wizard to create a new interface named Dutiable in the part2 package.

    Add two methods to the interface:

    public double payDuty();
    public double getDutyRate();        
            

  2. Create a new class named SpeedBoat in the part2 package. The new class should implement the Dutiable interface. It does not need a main method.

    Complete the class to the following specifications:

    1. Define a field named price of type double.

    2. Implement the two interface methods. The duty rate for SpeedBoats is 7.5% of the price.

    3. Write a constructor that accepts the price and assigns it to the field.

  3. Create a class named ExoticReptile in the part2 package that implements the Dutiable interface. Complete the class:

    1. Define a field named price of type double.

    2. Implement the two interface methods. The duty rate for Exotic Reptiles is 11% of the price.

    3. Write a constructor that accepts the price and assigns it to the field.

  4. Create a new class named TestDutiable in the part2 package. This class should have a main method. Complete main:

    1. Create an ArrayList collection.

    2. Create a few SpeedBoat and ExoticReptile objects and store their references in the collection.

    3. Use an iteration loop to calculate the average duty and display it to the console.

      Hint: As you retrieve each object from the collection, cast the object reference to Dutiable.

  5. Run and test your program.

Part 3: Discriminating Based on an Interface

In this part, you will write a program that takes different action based on whether an object implements an interface or not.

Steps:

  1. Create a new package named part3 and copy all of the classes from part2 to the new package.

  2. Create a new class named GMOFruit in the part3 package. This new class should NOT implement the Dutiable interface.

  3. Edit TestDutiable and add a couple of GMOFruit objects to the collection in addition to the SpeedBoat and ExoticReptile objects.

  4. Run the program -- what happened? Why?

  5. Modify the iteration loop so it uses the instanceof operator to determine if each object is of type Dutiable before calling the payDuty method. Your code should look something like:

    Object o = iter.next();
    if (o instanceof Dutiable)
    {
        . . .
            

  6. Run and test.

Part 4: Reinforcement

In this part, you will work with a program that uses interfaces to reinforce the topics you learned in this lab.

Steps:

  1. Import the part4 directory from {Lab Installation Directory/starters/lab10 into the Lab10 project's src folder.

  2. Examine the MyWindow class. This class represents a Java Swing GUI window with a frame. Run the program to see what it does currently (it's not very exciting).

  3. Your job is to modify the program so that it responds to mouse clicks on the window by drawing the text "Hello" at the point where the mouse was clicked.

    Start by reading the JavaDoc about the java.awt.event.MouseListener interface -- note that it defines a method named mousePressed that the windowing system will call when the user clicks the mouse.

    Also read about the MouseEvent object that's passed on mousePressed -- especially note that it makes the mouse-click coordinates available.

  4. Modify the MyWindow class so that it implements the java.awt.event.MouseListener interface. Then save the file -- note that you have errors regarding the interface methods.

  5. Right-click on the editing view and use Eclipse's Source - Override/Implement Methods menu to generate empty methods for the interface.

  6. Complete the mousePressed method so that it draws "Hello" at the mouse-click coordinates. To draw to the window, you can use the java.awt.Graphics class's drawString method. You can retrieve a Graphics object, with this code:

    Graphics g = getGraphics();        
            

  7. Find the MyWindow constructor, and add this line above the call to setSize:

    addMouseListener(this);        
            

    This call registers the MyWindow object with the windowing system for mouse events.

  8. Run the program and test it by clicking the mouse on the window -- do you see the "Hello" text?