GymKirchenfeld/EF-IN2012/Probe3-L
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
= Probe 3 (Lösungen)=
Der Programm-Code besteht aus 4 Klassen:
i) Die Klasse Crayon.java repräsentiert einen allgemeinen Stift.
ii) Die Klasse ColoredPencil.java repräsentiert einen Farbstift.
iii) Die Klasse Pencil.java repräsentiert einen Bleistift.
iv) Die Klasse Box.java repräsentiert ein Etui, welches aus diversen Stiften besteht.
<code id=CodeCrayon>
// **************** Crayon.java ****************
public class Crayon {
protected String color;
public Crayon(String color) {
this.color = color;
System.out.println("Ein neuer Stift wurde ins Etui gelegt.");
}
public void write() {
System.out.println("Ich schreibe mit der Farbe " + this.color + ".");
}
public String getTypeOfCrayon() {
return "Ich bin ein allgemeiner Stift.";
}
public String getColor() {
return this.color;
}
public String toString() {
return this.getTypeOfCrayon() + " Ich habe die Farbe " +
this.getColor();
}
}
</code>
<code>
// **************** ColoredPencil.java ****************
public class ColoredPencil extends Crayon {
public ColoredPencil(String color) {
super(color);
}
public void setColor(String color) {
this.color = color;
}
public String getTypeOfCrayon() {
return "Ich bin ein Farbstift.";
}
}
</code>
<code>
// **************** Pencil.java ****************
public class Pencil extends ColoredPencil {
public Pencil() {
super("schwarz");
System.out.println(this.getColor());
}
public String getTypeOfCrayon() {
return "Ich bin ein Bleistift.";
}
}
</code>
<run>
// **************** Box.java ****************
public class Box {
public Box() {
Pencil bleistift = new Pencil();
// Crayon lieblingsFarbstift = new ColoredPencil("gelb");
ColoredPencil lieblingsFarbstift = new ColoredPencil("gelb"); // richtige Deklaration
System.out.println(bleistift.getTypeOfCrayon());
lieblingsFarbstift.write();
lieblingsFarbstift.setColor("grün"); // Zusatz
lieblingsFarbstift.write(); // Zusatz
System.out.println(bleistift.toString());
}
public static void main(String[] args) {
new Box();
}
}
</run>
=== Aufgabe A1 ===
* Attribute: color
* Methoden: Crayon, write, getTypeOfCrayon, getColor, toString
=== Aufgabe A2 ===
Wenn eine Klasse B von A erbt, dann hat die Klasse B automatisch alle Attribute und Methoden der Klasse A. Das Prinzip der Vererbung ermöglicht es, bestehende Klassen zu erweitern.
Vererbungen im Source-Code:
- ColoredPencil erbt von Crayon
- Pencil erbt von ColoredPencil (und also auch von Crayon)
=== Aufgabe A3 ===
1)
Ein neuer Stift wurde ins Etui gelegt.
schwarz
Ein neuer Stift wurde ins Etui gelegt.
Ich bin ein Bleistift.
Ich schreibe mit der Farbe gelb.
Ich bin ein Bleistift. Ich habe die Farbe schwarz
2)
lieblingsFarbstift.setColor(„grün“);
3)
Ja, Pencil erbt von ColoredPencil, weshalb Pencil ebenfalls die Methode setColor besitzt.