An Interface Is a Collection of Constants and Abstract Methods
Total Page:16
File Type:pdf, Size:1020Kb
Interfaces
An interface is a collection of constants and abstract methods.
An abstract method has a signature/prototype but no implementation.
Example: public interface Speaker { public void speak(); public void announce(String str); }
A class can implement an interface. The requirement for a class to do so is that it provides definitions for each abstract method in the interface. Note that the class can have extra methods not listed in the interface.
Here is an example: public class Philosopher implements Speaker {
public String philosophy;
public Philospher(String thoughts) { philosophy = thoughts; }
public void speak() { System.out.println(philosophy); } public void announce(String announcement) { System.out.println(announcement); }
public void pontificate() { for (int i=0; i<5; i++) System.out.println(philosophy); } }
Thus, you MAY instantiate a Philosopher object after this code is written, but not a Speaker object. (You CAN however use a Speaker reference!!!) Also, multiple classes can implement the same interface and one class can implement multiple interfaces (e.g. public class Philosopher implements Speaker, Student).
Interfaces allow for polymorphism:
Imagine a class Dog as follows: public class Dog implements Speaker { ... }
Now we can declare a Speaker reference, which can both reference a Dog and a Philosopher object:
Speaker current; current = new Dog(); current.speak(); current = new Philosopher("I think, I think?"); current.speak(); ((Philosopher)current).pontificate();
Since pontificate is NOT in the speaker interface, a cast must be used before it can be called on the object current references. Note on Polymorphism
Keep in miund that polymorphism is possible through dynamic binding. The decision of which speak() to call is made a run- time and not compile time. This is less efficient than a static binding (made at compile time), but allows for extra flexibility, so it's worth it.
You can also make use of polymorphism by passing a parameter into a method: public void sayIt(Speaker current) { current.speak(); }
Java has a couple of common predefined interfaces: Comparable and Iterator. These are both discussed in the text. Abstract Classes
These are similar to interfaces, but CAN define methods and variables. However, typically some of the methods are left to be abstract. Also, you can NOT instantiate an object of an abstract class. (This is also true of an interface!!!)
Here is an example: public abstract class Vehicle }
protected String maker; protected String model; protected double insurance;
public Vehicle(String mak, String mod, double ins) { maker = mak; model = mod; insurance = ins; }
public String toString() { return maker + " " + model; }
public abstract drive(); }
Any class that inherits from Vehicle MUST define the method drive().