Interfaces and implementations
Abstract classes
Classes may be abstract, meaning they cannot be instantiated. Abstract classes are used when we have an "incomplete" class that we expect subclasses to "finish", or when a set of classes will share common code.
Abstract classes may (but are not required to) have abstract methods, which are simply bodiless methods with the keyword "abstract" prepended. Concrete (non-abstract) subclasses must provide the bodies of these methods.
Interfaces
If C implements D, then:
- D must be an interface. Interfaces may not define method bodies or data members, and all methods must be non-static. All methods in an interface are implicitly public.
- C must either be abstract or implement all methods defined in D.
import java.io.*; import java.util.Date; interface LogPrinter { public void log(String s); } abstract class AbstractLogPrinter implements LogPrinter { public void log(String s) { print(new Date() +": "+s); } public abstract void print(String s); // For subclasses } class StdoutLogPrinter extends AbstractLogPrinter { public void print(String s) { System.out.println(s); } } class FileLogPrinter extends AbstractLogPrinter { private PrintStream out; public FileLogPrinter(String filename) throws FileNotFoundException { out = new PrintStream(new FileOutputStream(filename)); } public void print(String s) { out.println(s); } }