Shape.java
public abstract class Shape {
private String name;
public Shape(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract double calcArea();
}
Rectangle.java
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle(String name, int width, int height) {
super(name);
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public double calcArea() {
return getWidth()*getHeight();
}
}
Circle.java
public class Circle extends Shape {
private static final double PI = 3.141592;
private int radius;
public Circle(String name, int radius) {
super(name);
this.radius = radius;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double calcArea() {
return PI*radius*radius;
}
}
Triangle.java
ShapeApplication.java
public class ShapeApplication {
public static void main(String[] args) {
// Shape myShape = new Shape();
Circle myCircle = new Circle("동그라미", 9);
System.out.println(myCircle.calcArea());
Shape myShape = new Rectangle("네모", 3, 2); //polymorphic object
// Virtual Method Invocation
System.out.println("사각형 넓이는 " + myShape.calcArea());
myShape = myCircle;
System.out.println("원의 넓이는 " + myShape.calcArea());
// Heterogeneous collection
Shape[] shapes = new Shape[2];
shapes[0] = myCircle;
shapes[1] = new Rectangle("직사각형", 5, 4);
Object[] objs = new Object[3];
objs[0] = "Hello";
objs[1] = myCircle;
objs[2] = 100;
Shape shapeObject = (Shape)objs[1];
System.out.println(shapeObject.calcArea());
}
}
|