Interfaces & Abstract Classes (For CS III AP) March 2014
Definitions Interface – collection of methods for which all ‘members’ must have implementations What are members ? – any classes implementing the Interface Interfaces are often very general nouns, such as a Shape interface, a Sports interface, which can in theory be used in a wide variety of applications (not just to one program) ^In this sense it is different from extending a superclass In fact, an interface cannot even be instantiated, so it cannot have a Constructor
Defining an Interface public interface interfaceName (e.g. Shape ) { /*method signatures & return types *are listed*/ public int getPerimeter(); public int getArea (); public void printName (); … } All of these are ‘abstract’ methods since they do not have a given implementa- tion *More specifically, they are given implementations in the class implementing the Interface.
An Example Class (Implementing the Interface) public class className (e.g. Rectangle ) implements Shape { /*method implementations and data *are listed*/ int width, height; // Assume a Constructor already exists public int getPerimeter() { return ((2 * width) + (2 * height)); } public int getArea () { return width * height; } public void printName () { System.out.println (“Rectangle”); } … } Here’s a challenge: What if we wanted to make a.toString() method instead?
Examples Comparable – very common example of Interface in CS III (and later CS classes!) – What are the methods in this example? obj1.compareTo (Object obj2); Returns -1, 0, or 1 if obj1 has a value less than, equal to, or greater than that of obj2 There are other Interfaces as well! – Collection, Set, Map, etc. – Data Structures – Runnable – threaded programming
Other Important Interface Laws Never write: Shape thisShape = new Shape(); No data fields are included in interfaces, except constants (static final). No methods can be implemented directly in an interface; all must be abstract. A class can extend (have a formal Is-A relationship with) only one superclass, but it may implement multiple interfaces
UML Diagrams Help Specify These Class Relationships
An Alternative to Interfaces Abstract classes –alternatives to interfaces, but different in many ways: – More application-specific – Can include some implementations and/or data fields – However – you still cannot create an instance of an abstract class; subclasses are expected to be used. (Teukolsky 139)
Thank you very much This will be posted on the CS Club website: Any questions? Next meeting will be 27 th March. Some other Sources, for your Interest: – erface.html erface.html – nterface.html nterface.html – m m