[ ^ CSE 341 | section index | <-- previous | next -->]

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:

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); } }

Last modified: Wed Apr 26 18:24:32 PDT 2000