Damit ein Interface mit »Leben« gefüllt wird,
muss es von einer Klasse implementiert werden. Für die Implementierung eines
Interface wird nicht extends benutzt, sondern
es gibt das speziell für diesen Zweck bestimmte Schlüsselwort implements.
Zunächst sei das Interface GraphObj von einer Klasse Point
implementiert:
public class Point implements GraphObj {
int x, y;
int color;
public Point(int x, int y, int color) {
this.x = x;
this.y = y;
setColor( color );
show();
}
protected void drawPoint(int x, int y, int color)
...
protected int getBackgroundColor()
...
public void setColor(int color) {
this.color = color;
}
public void show() {
drawPoint(x, y, color);
}
public void hide() {
drawPoint(x, y, getBackgroundColor());
}
}
Prinzipiell spielt es keine Rolle, ob die Klasse den Methoden des Interface tatsächlich eine Funktionalität verleiht oder sie einfach leer implementiert. Daher ist die anschließende Deklaration absolut zulässig.
class Dummy implements GraphObj {
public void setColor(int color) {}
public void show() {}
public void hide() {}
}
Wichtig ist nur, dass folgende Grundregel eingehalten wird: