GymKirchenfeld/EF-IN2012/Probe3-L
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Java</language>
= 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="4f4f276402bdf">
// **************** Crayon.java ****************
public class Crayon {
public 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(); // Aufgabe A4.2
}
}
// **************** 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.";
}
}
// **************** Pencil.java ****************
public class Pencil extends ColoredPencil {
public Pencil() {
super("schwarz");
System.out.println(this.getColor());
}
public String getTypeOfCrayon() {
return "Ich bin ein Bleistift.";
}
}
// **************** Box.java ****************
public class Box {
public Box() { // Aufgabe A4.4
Pencil bleistift = new Pencil(); // Aufgabe A4.3
ColoredPencil lieblingsFarbstift = new ColoredPencil("gelb");
System.out.println(bleistift.getTypeOfCrayon());
lieblingsFarbstift.write(); // Aufgabe A4.1
lieblingsFarbstift.setColor("grün"); // Aufgabe A3.2
lieblingsFarbstift.write(); // Aufgabe A3.2
System.out.println(bleistift.toString());
}
public static void main(String[] args) {
new Box();
}
}
</code>
=== 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.