class Shape {
private String color;
// 親クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Shape(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
class Rectangle extends Shape {
private int width;
private int height;
// åクラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Rectangle(String color, int width, int height) {
// 親クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’明示的ã«å‘¼ã³å‡ºã™
super(color);
// åクラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹å¤‰æ•°ã‚’åˆæœŸåŒ–
this.width = width;
this.height = height;
}
// 矩形ã®é¢ç©ã‚’計算ã™ã‚‹ãƒ¡ã‚½ãƒƒãƒ‰
public int calculateArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
// Rectangle クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’生æˆ
Rectangle rectangle = new Rectangle("Blue", 5, 10);
// 親クラスã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’使用ã—ã¦è‰²ã‚’å–å¾—
System.out.println("Shape color: " + rectangle.getColor());
// åクラスã®ãƒ¡ã‚½ãƒƒãƒ‰ã‚’使用ã—ã¦é¢ç©ã‚’å–å¾—
System.out.println("Rectangle area: " + rectangle.calculateArea());
}
}
ã“ã®ä¾‹ã§ã¯ã€Rectangle クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿å†…ã§ super(color) を使用ã—ã¦ã€Shape クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’呼ã³å‡ºã—ã¦ã„ã¾ã™ã€‚
「014 継承ã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント