1. T/F (a) Any class that implements an interface must have all the interface’s methods. (b) More than one class can implement the same interface. (c) Object a of class Foo that implements InterfaceA can be instantiated (initialized) by doing the following: InterfaceA a = new Foo(); (d) Interfaces can help eliminate redundancy in code. (e) Interfaces never specify constructors. (f) Every object is associated with an interface and a class. (g) Different classes that implement the same interface may also have different and additional methods not specified by that interface. (h) Many classes implementing a common interface is an example of polymorphism. 2. Given an Animal interface, three classes (Puppy, Bunny, Kitten), and a main method at the end for using them, answer questions (a) – (d) public interface Animal { public void speak(); } public class Puppy implements Animal{ public void bark() { System.out.println("arf"); } } public class Bunny { public void speak() { System.out.println("..."); } }
speak()
implements Animal
public class Kitten implements Animal{ public void speak() { System.out.println("meow"); } public void catchButterfly() { System.out.println("Catching butterflies..."); } }
public static void main(String[] args) { // write code for (b) here Animal[] animals = new Animal[3]; animals[0] = new Puppy(); animals[1] = new Kitten(); animals[2] = new Bunny(); for (int i = 0; i < animals.length; i++) { animals[i].speak(); }
} (a) The three classes should all implement the Animal interface. Did each class implement the interface correctly? If not, identify and fix the error(s). No. See the code above.
(b) Suppose all errors in (a), if any, are corrected. In the main method, write code that fulfills the following requirements: (1) create an Animal array of length 3, (2) initialize the first element in the array with a Puppy object, (3) initialize the second element in the array with a Kitten object, (4) initialize the last element in the array with a Bunny object, (5) write a loop that iterates through all the elements and invoke the speak method on each of them. (c) Write out the output printed after the main method in (b) runs. arf meow …
(d) In your own words, what is an interface? What do we gain from having classes implement an interface? An interface is a named group of one or more method declarations. Write more generic code. Model more complex relationships between objects