import java.util.ArrayList;
import java.util.List;
// Drawable インターフェイス
interface Drawable {
void draw();
}
// Circle クラス
class Circle implements Drawable {
// メンãƒãƒ¼å¤‰æ•°
private Point center; // ä¸å¿ƒåº§æ¨™
private double radius; // åŠå¾„
// コンストラクタ
public Circle(Point center, double radius) {
this.center = center;
this.radius = radius;
}
// draw メソッドã®å®Ÿè£…
@Override
public void draw() {
System.out.println("Drawing a circle with center at " + center + " and radius " + radius);
}
}
// Rectangle クラス
class Rectangle implements Drawable {
// メンãƒãƒ¼å¤‰æ•°
private Point topLeft; // 左上ã®åº§æ¨™
private double width; // å¹…
private double height; // 高ã•
// コンストラクタ
public Rectangle(Point topLeft, double width, double height) {
this.topLeft = topLeft;
this.width = width;
this.height = height;
}
// draw メソッドã®å®Ÿè£…
@Override
public void draw() {
System.out.println("Drawing a rectangle with top left corner at " + topLeft +
", width " + width + ", and height " + height);
}
}
// DrawingBoard クラス
class DrawingBoard {
// メンãƒãƒ¼å¤‰æ•°
private List<Drawable> shapes;
// コンストラクタ
public DrawingBoard() {
this.shapes = new ArrayList<>();
}
// addShape メソッドã®å®Ÿè£…
public void addShape(Drawable shape) {
shapes.add(shape);
}
// æç”»ãƒœãƒ¼ãƒ‰ä¸Šã®ã™ã¹ã¦ã®å›³å½¢ã‚’æç”»ã™ã‚‹ãƒ¡ã‚½ãƒƒãƒ‰
public void drawAllShapes() {
for (Drawable shape : shapes) {
shape.draw();
}
}
}
// Point クラス(座標を表ã™ã‚¯ãƒ©ã‚¹ï¼‰
class Point {
// メンãƒãƒ¼å¤‰æ•°
private double x;
private double y;
// コンストラクタ
public Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
ã“ã®è§£ç”例ã§ã¯ã€Drawable インターフェイスを実装ã—㟠Circle クラス㨠Rectangle クラスãŒã‚りã¾ã™ã€‚ã“れらã®å›³å½¢ã‚’ DrawingBoard クラスã§ç®¡ç†ã—ã€addShape ãƒ¡ã‚½ãƒƒãƒ‰ã§æç”»ãƒœãƒ¼ãƒ‰ã«è¿½åŠ ã§ãã¾ã™ã€‚drawAllShapes メソッドを呼ã³å‡ºã™ã“ã¨ã§ã€æç”»ãƒœãƒ¼ãƒ‰ä¸Šã®ã™ã¹ã¦ã®å›³å½¢ã‚’æç”»ã§ãã¾ã™ã€‚
「018 オブジェクト指å‘ã®æ·±åŒ–ã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント