6.2 KiB
6.2 KiB
title | author | date | wordtwit_post_info | categories | |||
---|---|---|---|---|---|---|---|
ポリモーフィズムの練習 | kazu634 | 2008-05-21 |
|
|
とりあえず研修ではオブジェクト指向の考え方まで学び終わったところです。やってみると以外に理解できたというのが感想。ポリモーフィズムの練習に作ったソースを貼り付けておきますね。
- Test.java
-
Shape.java (–> インターフェース)
- Circle.java
- Square.java
- Triangle.java
- Trapezium.java
public class Test { public static void main(String args[]) { Shape shp[] = new Shape[4]; double sum = ; shp[] = new Circle(5); shp[1] = new Square(10); shp[2] = new Trapezium(3, 5, 5); shp[3] = new Triangle(2, 2.5); for (int i = ;i < shp.length;i++) { shp[i].show(); sum += shp[i].getArea(); } System.out.println("========="); System.out.println("面積の合計: " + sum); } }
public interface Shape { public static final double PI = 3.14; public abstract double getArea(); public abstract void show(); }
public class Circle implements Shape { private double radium; public Circle(double r) { this.radium = r; } public double getArea() { return(radium * radium * PI); } public void show() { System.out.println ("円の面積: " + getArea()); } }
public class Square implements Shape { private double side; public Square(double side) { this.side = side; } public double getArea() { return(side * side); } public void show() { System.out.println ("正方形の面積: " + getArea()); } }
public class Triangle implements Shape { private double side; private double height; public Triangle(double side, double height) { this.side = side; this.height = height; } public double getArea() { return(side * height / 2); } public void show() { System.out.println ("三角形の面積: " + getArea()); } }
class Trapezium implements Shape { private double upper; private double lower; private double height; public Trapezium(double upper, double lower, double height) { this.upper = upper; this.lower = lower; this.height = height; } public double getArea() { return (upper + lower) * height / 2; } public void show() { System.out.println ("台形の面積: " + getArea()); } }