Q3. Classes More 1
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 thenoise()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();
}
-
Make a
BoorFanclass that implements the SportsFan interface. ABoorFandoes not cheer, so just return the empty string for that method. ABoorFanreturns"You stink!"when booing. -
A
DolphinFansays"flip"to cheer and"glub"to boo. Make theDolphinFanclass. -
Make a
GetRowdyclass 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 } -
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? */ }