blog/content/post/2008/05/21/2008-05-21-00000929.md

6.3 KiB
Raw Blame History

title author date url wordtwit_post_info categories
ポリモーフィズムの練習 kazu634 2008-05-21 /2008/05/21/_1001/
O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:4033;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}
java
Programming

 とりあえず研修ではオブジェクト指向の考え方まで学び終わったところです。やってみると以外に理解できたというのが感想。ポリモーフィズムの練習に作ったソースを貼り付けておきますね。

  • 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());
}
}