2016년 1월 28일 목요일

[JAVA 교육] 접근제한자 / 다형성 - 실습예제2

[ Class Diagram ]



[소스코드 : PolyApplication.java]
package sk.didimdol.oop.polymorphism;

public class PolyApplication {
    public static void main(String[] args) {
        Shape s = null;// = new Shape(10,20);  //abstract으로 만들어버려서 에러남
        s = new Circle(3,5,10);
        Shape s2 = new Circle(20,30,50);
        Rectangle r1 = new Rectangle(3,5,10,20);
        Shape s3 = r1;//다형적 객체

        Shape[] shapeList = new Shape[3];
        shapeList[0] = s;
        shapeList[1] = new Circle(4,5,10);//가능하다. is-a 관계이므로
        shapeList[2] = r1;

        for(Shape shape : shapeList){
            shape.draw();
        }

        Shape s4 = new Circle(6,7,20);
        s4.draw();      //Circle(자식)의 draw 호출
        Object obj = new Rectangle(3,4,10,20);
        Rectangle r3 = (Rectangle)obj;
        r3.draw();
        System.out.println(r3.calcArea());
        System.out.println(s4.calcArea());
        //Shape에 calcArea()가 없어서 에러
        //그래서 Shape에 abstract calcArea만들어주고 클래스명 앞에도 abstract붙여야한다.

        System.out.println();
    }
}

abstract class Shape {
    int x;
    int y;

    public Shape(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public void draw() {
        System.out.println(x+", "+y+" 위치에 도형을 그립니다.");
    }

    public abstract double calcArea();
}

class Circle extends Shape{
    int radius;

    public Circle(int x, int y, int radius) {
        super(x, y);
        this.radius = radius;
    }

    @Override
    public void draw() {
        super.draw();
        System.out.println("원을 그립니다.");
    }

    public double calcArea() {
        return radius * radius * 3.141592;
    }
}

class Rectangle extends Shape{
    int width;
    int height;

    public Rectangle(int x, int y, int width, int height) {
        super(x, y);
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        super.draw();
        System.out.println("사각형을 그립니다.");
    }

    public double calcArea() {
        return width * height;
    }
}

댓글 없음:

댓글 쓰기