Q3. Classes More 1

Writing classes, some review problems.

We have NoisyDog and SportsFan classes to practice working with abstract classes and implementing interfaces.

NoisyDog

Write the abstract class Noisy and the subclass NoisyDog.

  • The constructor should take in a number N that represents how many times it makes a noise. Remember the number N to use later.

  • The noise() method will make the (unspecified) noise one time. It is abstract because the noise is not specified and there is no good “default”.

  • The makeNoise() method repeats the noise() N times. This method is not abstract.

      public abstract class Noisy {
          // add any variables you need
          public Noisy (int n) { /* ... */ }
    
          // purpose: print the designated noise one time
          public abstract void noise();
    
          // print the designated noise N times
          public void makeNoise();
      }
    

The NoisyDog is a subclass of Noisy.

  • NoisyDog(String barknoise) constructor causes the object to remember what noise it will make, and sets up the object to make the noise three times.

  • The noise() method prints that noise.

  • NoisyDog() constructor by default makes the noise “bark” and the number of times the noise is made 3.

      public class NoisyDog extends Noisy {
          public NoisyDog();
          public void noise();
          public NoisyDog(String barknoise);
      }
    

What would happen if you left out the noise() method?

SportsFan

The SportsFan interface is:

    public interface SportsFan {
        String cheer();
        String boo();
    }
  1. Make a BoorFan class that implements the SportsFan interface. A BoorFan does not cheer, so just return the empty string for that method. A BoorFan returns "You stink!" when booing.

  2. A DolphinFan says "flip" to cheer and "glub" to boo. Make the DolphinFan class.

  3. Make a GetRowdy class that cheers twice, separated by spaces, when asked to cheer. It boos three times.

     public class GetRowdy implements SportsFan {
        // you might need instance variables
        public GetRowdy (SportsFan who) {
             // write this constructor
         }
         // other methods are required
     }
    
  4. The following code has some OK parts and some errors. Which lines are errors? If a line is not an error, explain what happens when you call the cheer() method of that object.

     public void demo() {
         SportsFan s = new SportsFan();  // 1
         SportsFan t = new BoorFan();    // 2
         BoorFan b = new SportsFan();    // 3
         GetRowdy r = new GetRowdy();    // 4
         GetRowdy rr = new GetRowdy(t);  // 5
         GetRowdy d =
            new GetRowdy(new DolphinFan()); // 6
    
         /* Call cheer() on all of them. What do they do? */
     }
    
Last modified March 17, 2025: Added details. (0e098a5)