Kursinhalt
C# Über die Grundlagen Hinaus
C# Über die Grundlagen Hinaus
3. Einführung in die Objektorientierte Programmierung (OOP)
Polymorphismus Üben
Das unten angegebene Programm enthält eine Superklasse namens Shape
und drei abgeleitete Klassen namens Rectangle
, Square
und Circle
. Das Problem mit dem Code ist, dass die Methoden nicht richtig überschrieben sind, da die Ausgabe 0.0
für alle drei Console.WriteLine
-Anweisungen zeigt, was impliziert, dass die Methoden der Basisklasse ausgeführt werden, anstatt der Methoden der abgeleiteten Klasse.
Bearbeiten Sie den Code so, dass die beiden Methoden, nämlich getArea
und calculatePerimeter
, korrekt überschrieben werden.
index
using System; using System.Collections.Generic; class Shape { // Perimeter is the length of the 'outline' of a shape public float perimeter; // Change code below this line public float getArea() { return 0.0f; } protected float calculatePerimeter() { return 0.0f; } // Change code above this line } class Rectangle : Shape { float width; float height; public Rectangle(float width, float height) { this.width = width; this.height = height; this.perimeter = this.calculatePerimeter(); } // Change code below this line public float getArea() { return width * height; } protected float calculatePerimeter() { return width * 2 + height * 2; } // Change code above this line } class Square : Shape { float length; public Square(float length) { this.length = length * length; this.perimeter = calculatePerimeter(); } // Change code below this line public float getArea() { return length * length; } protected float calculatePerimeter() { return 4 * length; } // Change code above this line } class Circle : Shape { float radius; public Circle(float radius) { this.radius = radius; this.perimeter = calculatePerimeter(); } // Change code below this line public float getArea() { return 3.14f * radius * radius; } protected float calculatePerimeter() { return 2.00f * 3.14f * radius; } // Change code above this line } class ConsoleApp { static void Main() { List<Shape> shapes = new List<Shape>(); shapes.Add(new Rectangle(10f, 20f)); shapes.Add(new Square(10f)); shapes.Add(new Circle(10f)); foreach (Shape shape in shapes) { Console.WriteLine(shape.getArea()); } } }
War alles klar?
Danke für Ihr Feedback!
Abschnitt 5. Kapitel 5