Sie sind auf Seite 1von 12

Schwerpunkte

• Aufgaben des Interface


8. Grundkonzepte
• Java-Interface als Abstraktion
der Objektorientierung (5):
• Implementation von Interfaces: implements
• Interface: wirkt wie neuer Typ
Interfaces
(Variablen vereinbaren u.a.)
• Interface: Spezialfall abstrakter Klassen
Java-Beispiele:
• Mit Interfaces:
ScheduleInt.java (eingeschränkte) Mehrfachvererbung in Java
ScheduleAbstr.java
UmkehrungNU.java • Typische Anwendungsfälle
KeyboardIApp.java
Druck.java

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 Version: 17. Jan. 2006 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 2

Java-Programm:
Menge von Komponenten

Interface: C1 C2

Überblick und Grundprinzip C3 C4

C5
C1

Komponente Ci: Klasse oder Interface

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 3 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 4
Komponenten in Java Java-Syntax: Komponentenarten
zwei Arten
(zumindest syntaktisch)
Quelltextdatei ::=
Klasse Interface [Paketfestlegung]
class interface {Import}
{Typdeklaration}

wird implementiert durch


Typdeklaration ::=
(spezielle) abstrakte Klasse Klassendeklaration |
Schnittstellendeklaration .
Klassenkonzept kann Interface benötigt
Interface modellieren Klassenkonzept

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 5 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 6

Beispiel: volle Form der Quelltextdatei Rolle von Java-'interface'-Komponenten


package demo;

import java.util.*
• Inhaltlich-logische Funktion:
class C1 {
... - Trennung Interface - Implementation
}

interface I1 {
... • Technische Funktion:
} - eingeschränkte Mehrfachvererbung
Definition einer Komponente C1/I1 kann voraussetzen:

- package: Zuordnung zu einem Paket


(Sammlung von Klassen mit ähnlichen Aufgaben)

- import: Paket angegeben, aus dem Klassen verwendet


werden sollen
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 7 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 8
SW-Komponenten sind Abstraktionen Java-Klasse: Wo ist die Abstraktion?
Komponente: Interface + Implementation
class Time {

private int hour, minute;


...
SW – "Restsystem" public void addMinutes (int m) {

int totalMinutes =
(60*hour + minute + m) % (24 * 60);
if (totalMinutes < 0)
totalMinutes = totalMinutes + 24 * 60;
Schnittstelle zur hour = totalMinutes / 60;
Interface "Außenwelt" ...
}
... Java-Klasse ist Mischung aus
Implementation Hiervon kann die Interface und Implementation:
}
"Außenwelt" Abstraktionsprinzip nicht umgesetzt
("versteckt") abstrahieren
- Interface - Implementation

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 9 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 10

Interface eines ADT C++-Klasse: eine Abstraktion ?


class Time {
SW – "Restsystem"
public: Konsequenz: Klassen
Time (); in C++ sind bessere
Time (int h, int m); Abstraktionen als
Klassen in Java
void addMinutes (int m);
Interface: Signatur void printTime ();
Operationen aller Operationen
des ADT ...
Implementation:
("versteckt")
private: Aber: Java-Interface
• Art der Daten- int hour, minute; überwindet diesen
darstellung, z.B. Mangel
int [] sort; Hiervon kann die }
"Aussenwelt"
• Implementation abstrahieren
der Operationen - Interface - Implementation
(Algorithmen)

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 11 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 12
Java–Interface:
eine (fast) "saubere" Abstraktion
Sc
he
du
l eI
interface TimeI { nt.
jav
Interface in Java:
public void addMinutes (int m); a
public void substractMinutes (int m);
public void printTime ();
- Definition public void printTimeInMinutes ();
}
- Implementation
• Nur die Köpfe der Methoden
- Anwendung • Keine Daten + keine Algorithmen
• Was fehlt?
- Vergleich mit abstrakten Klassen Konstruktoren (im Interface nicht erlaubt):

TimeI(int h, int m);


TimeI();

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 13 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 14

Implementation eines Interface


durch Klassen
Anwendung eines Interface
Sc
Nutzer interface TimeI { he
du
public void addMinute (int m);
l eI interface TimeI { class Time implements TimeI {
public void substractMinutes (int m); nt. public void addMinute (int m); private int hour, minute;
public void printTime (); jav public void substractMinutes (int m); public Time (int h, int m)
public void printTimeInMinutes ();
a public void printTime (); public void addMinutes (int m)
public void printTimeInMinutes (); ...
} } }

class Time implements TimeI { Sc


he
private int hour, minute; Interface wie neuer (nutzerdefinierter) Typ du
l eI
nt
Nutzer muss public Time (int h, int m) {...}
public static void main (...) { . ja
auch von public void addMinutes (int m) { Variablen vom va
implemen- int totalMinutes = Interface-Typ
TimeI t1;
tierender 'TimeI'
(60*hour + minute + m) % (24 * 60);
Klasse t1 = new Time(8,30);
kennen:
if (totalMinutes < 0)
totalMinutes = totalMinutes + 24 * 60; Erlaubte Werte: t1.addMinutes(30);
Name, Konstruktor
Konstruktoren hour = totalMinutes / 60; Objekte von ALLEN }
Hinzugefügt: implementierenden identifiziert
... ausgewählte
} • Lokale Variablen Klassen
• Konstruktor (Kompatibilitätsregel) implementierende
... Klasse
• Körper der Methoden
}
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 15 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 16
Interface:
Rolle von Java-'interface'-Komponenten
Spezialfall abstrakter Klassen
Sche • Inhaltlich-logische Funktion
d ul e - Trennung Interface - Implementation
Abst
abstract class TimeI { r.jav
public abstract void addMinutes (int m); a public static void main (...)
public abstract void substractMinutes (int m); {
public abstract void printTime (); TimeI t1;
public abstract void printTimeInMinutes(); t1 = new Time(8,30);
} ...
} Nutzerkomponente
class Time extends TimeI {
private int hour, minute;
Als eine logische Einheit auffassen:
public void addMinutes (int m); {
...
interface TimeI (...)
}
... class Time implements TimeI{...}
}

Interface und abstrakte Klasse: • Technische Funktion:


logisch identisch – technische Unterschiede - eingeschränkte Mehrfachvererbung

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 17 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 18

Interface:
eingeschränkte Mehrfachvererbung
für Klassen verboten – für Interface erlaubt:

Komponente 1 Komponente 2

Mehrfachvererbung in Java Vererbung


durch Interface-Komponenten
Komponente 3

(abstract) class K1 ...


(abstract) class K2 ... falsch
class K3 extends K1, K2 ...

interface I1 ...
interface I2 ... ok
class K3 implements I1, I2 ...
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 19 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 20
Beispiel: Beispiel:
Hierarchie mit Mehrfachvererbung (1) Hierarchie mit Mehrfachvererbung (2)

class class interface interface


Fahrzeug Sammlerstueck Fahrzeug Sammlerstueck

class class

Auto falsch Auto


OK

class class class class

Oldtimer Flugzeug Oldtimer Flugzeug

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 21 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 22

Beispiel: Vererbungshierarchie in Java Beispiel: volle Form


(nach: Krüger: Go To Java 2)
interface Fahrzeug ...
interface Fahrzeug { interface Sammlerstueck {
interface Sammlerstueck ... public int kapazitaet(); public double wert();
public double verbrauch(); public boolean ausgestellt();
} }
class Auto implements Fahrzeug ...
Erbt alle Elemente (Variablen,
class Auto implements Fahrzeug { class Oldtimer extends Auto
Methoden) von 'Auto' und
public String name; implements Sammlerstueck {
'Sammlerstueck' private int anzSitze; private double sammlerWert;
class Oldtimer extends Auto private double spritVerbrauch; private boolean ausst;
implements Sammlerstueck public int kapazitaet() public double wert ()
{ return anzSitze; } { return sammlerWert; }
public double verbrauch() public ausgestellt ()
Erbt alle Elemente von { return spritVerbrauch;} { return ausst; }
} }
'Fahrzeug' und Sammlerstueck'
class Flugzeug implements Fahrzeug,
Sammlerstueck class Flugzeug
implements Fahrzeug, Sammlerstueck ...

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 23 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 24
Interface: Interface:
Welche Komponentenart modelliert? modellierbare Komponentenart
Vgl. III.4 Komponentenarten

interface Fahrzeug {
public int kapazitaet();
public double verbrauch(); sinnlose viele
static final int anzahl = 100000; Konstruktionen semantisch
} sehr unterschiedliche
Komponenten a r t e n
Festlegung (gilt auch implizit für Interface):
Methoden: public, abstract, non-static
Variablen: public, static, final imperativ objektorientiert

Funktions- ADT
Konstanten-
Æ ADT mit Konstanten sammlung
sammlung Daten-
sammlung ADT mit
andere Daten- Konstanten
ADT mit
abstraktion Klassenelementen

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 25 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 26

Interface: Java-Interface:
nicht modellierbare Komponentenarten Methoden mit Interface-Parametern
interface TimeI {
public void addMinutes (int m);
public void printTime ();
...
Îsinnlose
Nicht für jede viele pulic boolean before (TimeI t);
Komponentenart
Konstruktionen semantisch } Dieselbe Signatur:
kann ein Interface sehr unterschiedliche Interface-Typ auch in Klasse
angeboten werden Komponenten a r t e n
class Time implements TimeI {

public boolean before ( TimeI t1 ) {


Time t = (Time) t1;
return ((hour < t.hour) || ...)
imperativ objektorientiert }

Funktions- ADT
Typ-Transformation: Parameter hat Interface-Typ
Konstanten- allgemeiner Typ (Interface) Æ spezieller Typ
sammlung
h sammlung Daten-
at ADT mit
.M andere sammlung Cast-Operation kann Laufzeitfehler erzeugen:
ng Daten- Konstanten
.la ADT mit
va abstraktion aktueller Parameter einer anderen
ja Klassenelementen
ss ClassCastException
cla rd implementierenden Klasse übergeben
bo a eC
K ey Ti m
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 27 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 28
Interface: Anwendungsfälle

• E i n Interface eines ADT


- z w e i (mehrere) Implementationen:
- UmkehrungNU.java: beschränkt und unbeschränkt

Interface: • Interface für Datenabstraktionen:


wichtige Anwendungen - KeyboardIApp.java

• Import gemeinsamer Konstanten von Klassen

• Algorithmen mit 'Funktionsparametern':


- Druck.java: Druck beliebiger Funktionen

• Java-API: List – Set – Collection ...

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 29 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 30

Java-API: Vielzahl von Interfaces Interface: Anwendungsfälle


Interface Collection
• E i n Interface eines ADT
Map - z w e i (mehrere) Implementationen:
Serializable Set
extends
- UmkehrungNU.java: beschränkt und unbeschränkt
List SortedSet
Cloneable
• Interface für Datenabstraktionen:
implements - KeyboardIApp.java
AbstractList

Vector LinkedList TreeSet HashTable


• Import gemeinsamer Konstanten von Klassen

extends
Klassen • Algorithmen mit 'Funktionsparametern':
Stack - Druck.java: Druck beliebiger Funktionen
public class Vector Mehrfachvererbung
durch Vielzahl von
extends AbstractList
implements List, Cloneable, Serializable Interfaces im Java-API
• Java-API: List – Set – Collection ...

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 31 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 32
E i n Interface eines ADT – Anwendung:
zwei (mehrere) Implementationen: nur Interface bekannt + Konstruktor
Um Um ke h
rungNU
interface Stack { ke interface Stack { .java
hr
public boolean isempty(); un public boolean isempty();
gN
public void push(char x); U. public void push(char x); Besonderheit von UmkehrungNU.java:
public char top(); j av Erst dynamisch wird die
a public char top();
Vorteil: pulic void pop(); pulic void pop(); implementierende Klasse ausgewählt
} } Æ dynamische Bindung von
Gute Methoden zur Laufzeit
Modifizierbarkeit, class StackN implements Stack { Anwendung:
falls die private char[] stackElements;
private int top;
Stack s; Auswechseln der
Anwendung nur
...
s = new StackN(n); Implementation:
mit den beschränkte Größe oder
} Nur der Konstruktor
Informationen aus
s = new StackU(); ist auszuwechseln
dem Interface Algorithmus korrekt
arbeitet class StackU implements Stack { für beliebige while (!s.isempty()) {
private class Zelle {...} Implementationen: System.out.print(s.top());
private Zelle top; - Begrenzte Stacks Methoden aus
unbeschränkt s.pop();
... - Unbegrenzte Stacks dem Interface
}
}
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 33 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 34

Interface: Anwendungsfälle Klasse 'Keyboard`: eine Datenabstraktion

• E i n Interface eines ADT import java.io.*; public static int readInt () {


- z w e i (mehrere) Implementationen: class Keyboard {
if (iseof) return 0;
System.out.flush();
- UmkehrungNU.java: beschränkt und unbeschränkt // Author: M. Dennis Mickunas,
try {
s = input.readLine();
// June 9, 1997 Primitive Keyboard }
// input of integers, reals, catch (IOException e) {
• Interface für Datenabstraktionen: // strings, and characters. System.exit(-1);
}
- KeyboardIApp.java static
static
boolean iseof = false;
char c;
if (s==null) {
iseof=true;
static int i; return 0;
static double d;
• Import gemeinsamer Konstanten von Klassen
}
static String s; i = new
Integer(s.trim()).intValue();
/* WARNING: THE BUFFER VALUE IS SET return i;
TO 1 HERE TO OVERCOME ** A KNOWN BUG
• Algorithmen mit 'Funktionsparametern': IN WIN95 (WITH JDK 1.1.3 ONWARDS)*/
}

- Druck.java: Druck beliebiger Funktionen Klasse realisiert


static BufferedReader input
public static char readChar () {
if (iseof) return (char)0;
= new BufferedReader (
Abstraktionsprinzip
new
nicht: System.out.flush();
...
Kein Interface für Nutzer
• Java-API: List – Set – Collection ...
InputStreamReader(System.in),1);
erkennbar Realisierung als Interface
möglich?
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 35 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 36
Interface:
Interface für Datenabstraktionen
modellierbare Komponentenart
Ke
yb
Interface für interface KeyboardI { oa
r dI
den Nutzer public int readInt(); Ap
public char readChar(); pl.
viele j av
sinnlose Datenabstraktion public double readDouble(); a
Konstruktionen semantisch nicht durch public String readString();
sehr unterschiedliche ‘interface‘ public boolean eof();
Komponenten a r t e n realisierbar Æ ADT }
jetzt: Instanzmethoden Æ ADT

Unwichtige class Keyboard implements KeyboardI {


imperativ objektorientiert Implementations- // 110 Zeilen Implementation
details }

Funktions- ADT
Konstanten-
sammlung
sammlung Daten- Anwendung: Keyboard kb = new Keyboard();
sammlung ADT mit technisch andere
andere Daten- Konstanten
ADT mit Realisierung Æ jn = kb.readChar();
abstraktion Klassenelementen Objekt erzeugt n = kb.readInt();
rd
bo a vgl. Keyboard.readChar()
K ey
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 37 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 38

Interface: Anwendungsfälle Import gemeinsamer Konstanten


Konstanten: Steuerzeichen
• E i n Interface eines ADT interface Steuerzeichen {
- z w e i (mehrere) Implementationen: public static final char BS = ’\b’,
- UmkehrungNU.java: beschränkt und unbeschränkt HT = ’\t’, LF = ’\n’,
FF = ’\f’, CR = ’\r’;
} 'implements' –
• Interface für Datenabstraktionen: ein adäquater
Konstanten verfügbar in Ausgabe1
- KeyboardIApp.java Begriff?
/ Ausgabe2
class Ausgabe1 implements Steuerzeichen {
• Import gemeinsamer Konstanten von Klassen // Methoden der Ausgabe 1
}

• Algorithmen mit 'Funktionsparametern': class Ausgabe2 implements Steuerzeichen {


- Druck.java: Druck beliebiger Funktionen // Methoden der Ausgabe 2
}

• Java-API: List – Set – Collection ... dieselbe Technik: include-Files in C / C++

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 39 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 40
Algorithmen mit 'Funktionsparametern'
Interface: Anwendungsfälle
Problem:
• Algorithmen: arbeiten mit (beliebigen)
• E i n Interface eines ADT mathematischen Funktionen
• Funktion ist Parameter des Algorithmus
- z w e i (mehrere) Implementationen:
- UmkehrungNU.java: beschränkt und unbeschränkt - Pascal: Funktionsparamter (spezielle Parameterart)
function druckeKurve (x0: real; x1: real;
• Interface für Datenabstraktionen: delta: real;
function F(x: real): real ) ...
- KeyboardIApp.java
Aufruf:
druckeKurve(0.5, 1.5, 0.1, sin);
• Import gemeinsamer Konstanten von Klassen druckeKurve(0.5, 1.5, 0.1, cos);

• Algorithmen mit 'Funktionsparametern': - C, C++: Zeiger auf Funktionen als Parameter


- Druck.java: Druck beliebiger Funktionen
- Java: Interface oder abstrakte Klassen *)
*) Funktionsparameter exisitieren nicht
• Java-API: List – Set – Collection ... Æ Parameter: elementare Typen oder Objekte
Æ Funktion in Interface "verpacken" (Wrapper für Funktion)
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 41 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 42

Beispiel: Beispiel:
Algorithmen mit 'Funktionsparametern' (1) Algorithmen mit 'Funktionsparametern' (2)
Dru
ck.j Dr
ava interface Function { uc
k.j
interface Function { double apply (double x); av
double apply (double x); allgemeinstes Schema } a
} einer einstelligen
reellwertigen Funktion Nutzer: arbeitet nur mit allgemeinem Schema (interface)
class SinFunction implements Function {
public double apply (double x) { static void druckeKurve (double x0, double x1,
return Math.sin(x); double delta, Function f) {
} System.out.print( f.apply(x0) ); ...
} }

2 Spezialisierungen: Sinus, Cosinus Anwendung: konkrete Funktionen 'sin', 'cos' Technisch anders
als in Pascal, C, ...:
public static void main (...) {
class CosFunction implements Function { Hier wird Objekt
SinFunction sinus = new SinFunction();
public double apply (double x) { übergeben, das
CosFunction cosinus = new CosFunction();
return Math.cos(x); passende Methode
druckeKurve(0, Math.PI/2, 0.1, sinus);
} umfasst
druckeKurve(0, Math.PI/2, 0.1, cosinus);
} (Wrapper)
}
K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 43 K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 44
Druck aller Funktionswerte von x0 bis x1
(Verbesserung von Druck.java)

static void druckeKurve (double x0,


double x1, double delta, Function f ) {

for (int x = x0; x<= x1; x = x+delta)


System.out.print( f.apply(x) );
...
}

K. Bothe, Inst. f. Informatik, HU Berlin, PI1, WS 2006/07 45

Das könnte Ihnen auch gefallen