課題 10
1. 次のプログラムコードを実行し(コピーペーストで構わない)
、なぜそのような結果に
なるのか考えなさい。Java を学習中の友達から、次のような質問を受けたと仮定し、
質問に対する答えを書きなさい。
(1) interface とは何ですか。
(2) Shape クラスに abstract が付いているのはなぜですか。付いていない場合と
何が違うのですか。
(3) Rectangle クラスに draw メソッドが無いとエラーになります。なぜですか。
(4) Rectangle クラスに getArea メソッドが無いとエラーになります。なぜです
か。
(5) main メソッドで Shape 型の配列に Rectangle や Circle、Polyline クラス
のインスタンスを代入していますが、なぜこのようなことができるのですか。
(6) if(shapes[i] instanceof HasGetAreaMethod)とありますが、この意味
を教えてください。
(7) HasGetAreaMethod closedShape = (HasGetAreaMethod)shapes[i];
とありますが、この意味を教えてください。
interface HasGetAreaMethod {
double getArea();
}
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape implements HasGetAreaMethod {
int width;
int height;
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
void draw() {
System.out.println("□");
}
public double getArea() {
return width * height;
}
}
class Circle extends Shape implements HasGetAreaMethod {
int radius;
Circle(int radius) {
this.radius = radius;
}
void draw() {
System.out.println("○");
}
public double getArea() {
return radius * radius * 3.14159;
}
}
class Polyline extends Shape {
void draw() {
System.out.println("N");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Shape[] shapes = new Shape[6];
shapes[0] = new Rectangle(2,5);
shapes[1] = new Circle(7);
shapes[2] = new Polyline();
shapes[3] = new Rectangle(3,8);
shapes[4] = new Circle(3);
shapes[5] = new Polyline();
for(int i = 0; i < shapes.length; i++) {
System.out.println(i + "番目の図形");
printOutShape(shapes[i]);
if(shapes[i] instanceof HasGetAreaMethod) {
HasGetAreaMethod closedShape = (HasGetAreaMethod)shapes[i];
printOutArea(closedShape);
} else {
System.out.println("面積を求められない図形");
}
}
}
static void printOutShape(Shape shape) {
System.out.println("図形の形");
shape.draw();
}
static void printOutArea(HasGetAreaMethod closedShape) {
System.out.println("図形の面積:" + closedShape.getArea());
}
}
© Copyright 2026 ExpyDoc