Interfaces
Introduction
Interfaces compared to abstract classes
A Printable interface
public interface Printable { public abstract void print(); }
A Printable abstract class
public abstract class Printable { public abstract void print(); }
Advantages of an abstract class
An abstract class can:
- Use instance variables and constants as well as static variables and constants.
- Include regular methods that contain code as well as abstract methods that don't contain code.
- Define static methods.
Advantages of an interface
- A class can only directly inherit one other class, but it can directly implement multiple interfaces.
- Any object created from a class that implements an interface can be used wherever the interface is accepted.
Class, subclass, abstract class, or interface
- Make a class that doesn't extend anything (other than Object) when your new class doesn't pass the IS-A test for any other type. (To know if you've designed your types correctly, ask, "Does it makes sense to say type X IS-A type Y?" If it doesn't, you know there's something wrong with the design.)
- Make a subclass (in other words extend a class) only when you need to make a morespecific version of a class and need to override or add new behaviors.
- Use an abstract class when you want to define a template for a group of subclasses, and you haveat least some implementation code that all subclasses could use. Make the class abstract when you want to guarantee that nobody can make objects of that type.
- Use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree.