ABSTRACT CLASSES VS. INTERFACES =============================== In the JDC Tech Tips for October 9, 2001 http://java.sun.com/jdc/JDCTechTips/2001/tt1009.html, there was an item about using an abstract class hierarchy to implement the Java equivalent of a C union. The code looked something like this: abstract class Time { public abstract int getMinutes(); } class Days extends Time { private int days; public int getMinutes() { return days * 24 * 60; } } class HoursMinutes extends Time { private int hours; private int minutes; public int getMinutes() { return hours * 60 + minutes; } } A reader asked why an interface could not be used instead of an abstract class, with the code written as follows: interface Time { int getMinutes(); } class Days implements Time { private final int days; public Days(int days) { this.days = days; } public int getMinutes() { return days * 24 * 60; } } class HoursMinutes implements Time { private final int hours; private final int minutes; public HoursMinutes(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } public int getMinutes() { return hours * 60 + minutes; } } public class AIDemo1 { public static void main(String args[]) { Time t1 = new Days(10); Time t2 = new HoursMinutes(15, 59); System.out.println(t1.getMinutes()); System.out.println(t2.getMinutes()); } } In fact, the interface approach does work. However, there are a series of tradeoffs between the use of abstract classes and interfaces. This tip examines some of those tradeoffs. Both of these mechanisms define a contract, that is, required behavior that another class must implement. If you have the following definitions: abstract class A { abstract void f(); } interface B { void f(); } then a concrete class that extends A must define f. A class that implements B must define f. Beyond this common feature, the two mechanisms are quite different. Interfaces provide a form of multiple inheritance ("interface inheritance"), because you can implement multiple interfaces. A class, by comparison, can only extend ("implementation inheritance") one other class. An abstract class can have static methods, protected parts, and a partial implementation. Interfaces are limited to public methods and constants with no implementation allowed. So what's the difference between using abstract classes and interfaces in the example above? One difference is that an abstract class is easier to evolve over time. Suppose that you want to add a method: public int getSeconds(); to the Time contract. If you use an abstract class, you can say: public int getSeconds() { return getMinutes() * 60; } In other words, you provide a partial implementation of the abstract class. Doing it this way means that subclasses of the abstract class do not need to provide their own implementation of getSeconds unless they want to override the default version. If Time is an interface, you can say: interface Time { int getMinutes(); int getSeconds(); } But you're not allowed to implement getSeconds within the interface. This means that all classes that implement Time are now broken, unless they are fixed to define a getSeconds method. So if you want to use an interface in this situation, you need to be absolutely sure that you've got it right the first time. That way you don't have to add to the interface at a later time, thereby invalidating all the classes that use the interface. Another issue with this example is that you might want to factor out common data into the abstract class. There is no equivalent to this functionality for interfaces. For example, if you say: interface A { int x = 7; } class B implements A { void f() { int i = x; // OK x = 37; // error } } all is well if you want to declare a constant in the interface, but it's not possible to declare a mutable data field this way. Let's look at another example: import java.io.*; interface Distance { double getDistance(Object o); } interface Composite extends Comparable, Distance, Serializable {} class MyPoint implements Comparable, Distance, Serializable { //class MyPoint implements Composite { private final int x; private final int y; public MyPoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public int compareTo(Object o) { MyPoint obj = (MyPoint)o; if (x != obj.x) { return x < obj.x ? -1 : 1; } return y < obj.y ? -1 : (y == obj.y ? 0 : 1); } public double getDistance(Object o) { MyPoint obj = (MyPoint)o; int sum = (x - obj.x) * (x - obj.x) + (y - obj.y) * (y - obj.y); return Math.sqrt(sum); } } public class AIDemo2 { public static void main(String args[]) { MyPoint mp1 = new MyPoint(1, 1); MyPoint mp2 = new MyPoint(2, 2); double d = mp1.getDistance(mp2); System.out.println(d); int cmp = mp1.compareTo(mp2); if (cmp < 0) { System.out.println("mp1 < mp2"); } else if (cmp == 0) { System.out.println("mp1 == mp2"); } else { System.out.println("mp1 > mp2"); } } } MyPoint is a class that represents geometric X,Y points, with the usual constructor and accessor methods defined. The class implements three interfaces. One interface is used to compare one point to another, one is used to compute the Euclidean distance between points, and the last declares that MyPoint objects are serializable. An alternate approach would be to define a new interface Composite (called a "subinterface") that extends the three interfaces, and then implement Composite in MyPoint. This is an example of a "nonhierarchical type framework". The output of the program is: 1.4142135623730951 mp1 < mp2 It's easy to retrofit an existing class to implement a new interface. Doing this is sometimes called a "mixin." In a mixin, a class declares that it provides some optional, side behavior in addition to its primary function. Comparable is an example of a mixin. Note that it would be awkward to implement the AIDemo2 example using abstract classes. Implementing several unrelated interfaces in a class is hard to duplicate using abstract classes. It's often desirable to combine interfaces and abstract classes. For example, part of the design of the Collections Framework looks roughly like this: interface List { int size(); boolean isEmpty(); } abstract class AbstractList implements List { public abstract int size(); public boolean isEmpty() { return size() == 0; } } class ArrayList extends AbstractList { public int size() { return 0; // placeholder } } At the top of the hierarchy are interfaces, such as Collection and List, that describe a contract, that is, a specification of required behavior. At the next level are abstract classes, such as AbstractList, that provide a partial implementation. Note that size is not defined in AbstractList, but that isEmpty is defined in terms of size. If a list has zero size, it is empty by definition. A concrete class, such as ArrayList, then defines any abstract methods not already defined. If you use this scheme, and program in terms of interface types (List instead of ArrayList), there are several benefits: o Much of the implementation work is already done for you in the abstract classes. o You can easily switch from one implementation to another (LinkedList instead of ArrayList). o If ArrayList or LinkedList are not satisfactory, you can develop your own class that implements List. o If you cannot extend a given class, because you're already extending another class, you can instead implement the interface for the desired class and then forward method calls to a private instance of the desired class. Interfaces tend to be a better choice than abstract classes in many cases, though you need to get the interface right the first time. Changing the interface after the fact will break a lot of code. Abstract classes are useful when you're providing a partial implementation. In this case, you should also define an interface as illustrated above, and implement the interface in the abstract class. For more information about abstract classes vs. interfaces, see Section 4.4, Working with Interfaces, and Section 4.6, When to Use Interfaces, in "The Java(tm) Programming Language Third Edition" by Arnold, Gosling, and Holmes http://java.sun.com/docs/books/javaprog/thirdedition/. Also see item 14, Favor composition over inheritance, and item 16, Prefer interfaces to abstract classes, in "Effective Java Programming Language Guide" by Joshua Bloch (http://java.sun.com/docs/books/effective/). . . . . . . . . . . . . . . . . . . . . . . .