جواب «Two Real Shapes» چالش 3 از جلسهی 24
سؤال
Shape یک کلاس abstract است: فقط یک ایده. برنامه دو شکل واقعی میخواهد که هنوز نوشته نشدهاند.
دو فرزند برای Shape بنویس:
- Rect: سازندهاش w و h میگیرد (هر دو number)، والد را با اسم "Rect" میسازد و area آن w * h است.
- Square: سازندهاش side میگیرد، والد را با اسم "Square" میسازد و area آن side * side است.Shape را دست نزن.
برنامه باید بنویسد: Rect area 12 و در خط بعد Square area 25
راهنما
class Rect extends Shape { constructor(private w: number, private h: number) { super("Rect"); } area(): number { return this.w * this.h; } }. Square هم مثل همین.
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>
<pre id="out"></pre>
<script type="text/typescript">
abstract class Shape {
constructor(public name: string) {}
abstract area(): number;
describe(): string {
return this.name + " area " + this.area();
}
}
class Rect extends Shape {
constructor(private w: number, private h: number) {
super("Rect");
}
area(): number {
return this.w * this.h;
}
}
class Square extends Shape {
constructor(private side: number) {
super("Square");
}
area(): number {
return this.side * this.side;
}
}
show(new Rect(3, 4).describe());
show(new Square(5).describe());
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن