ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (펌) 다형성에 관해서
    삼성SDS_멀티캠퍼스/Java 2015. 9. 21. 17:46
    반응형

    # 다형성이란?

    다양한 객체들을 하나의 코드로 처리하는 기술.

     

    Shape s = new Rectangle(); 다형성의 출발!

    서브클래스 객체는 수퍼 클래스 객체를 포함한다.

     

    동적 바인딩:  오버라아딩 된 메소드 중 실제로 가리키고 있는 Rectangle객체 의 타입의 메소드를 출력시킨다.

     

     

     
    public class Shape {
     protected int x;
     protected int y;
     
     public Shape(){
      x=y=0;
     }
     
     
     public void draw(){
      System.out.println("Shape 의 draw");
     }

     public int getX() {
      return x;
     }

     public void setX(int x) {
      this.x = x;
     }

     public int getY() {
      return y;
     }

     public void setY(int y) {
      this.y = y;
     }

     @Override
     public String toString() {
      return "Shape [x=" + x + ", y=" + y + "]";
     }
     
    }

     
    public class Rectangle extends Shape{
     private int height;
     private int width;

     public Rectangle() {
      
     }
     
     public void draw (){
      System.out.println("Rectangle 의 draw");
     }

     public int getHeight() {
      return height;
     }

     public void setHeight(int height) {
      this.height = height;
     }

     public int getWidth() {
      return width;
     }

     public void setWidth(int width) {
      this.width = width;
     }

     @Override
     public String toString() {
      return "Rectangle [height=" + height + ", width=" + width + "]";
     }

    }

     
    public class Circle extends Shape{
     private int radius;
     
     public Circle(){
      
     }
     
     public void draw(){
      System.out.println("Circle의 draw");
     }

     public int getRadius() {
      return radius;
     }

     public void setRadius(int radius) {
      this.radius = radius;
     }

     @Override
     public String toString() {
      return "Circle [radius=" + radius + "]";
     }
     
     
    }

     
    public class Triangle extends Shape {
     private int base;
     private int height;

     public Triangle() {

     }

     public void draw() {
      System.out.println("Triangle 의 draw");
     }

     public int getBase() {
      return base;
     }

     public void setBase(int base) {
      this.base = base;
     }

     public int getHeight() {
      return height;
     }

     public void setHeight(int height) {
      this.height = height;
     }

     @Override
     public String toString() {
      return "Triangle [base=" + base + ", height=" + height + "]";
     }

    }

     public class Test {
     private static Shape arrayOfShape[];

     public static void main(String[] args) {
      inti();
      drawAll();
     }

     public static void inti() {
      arrayOfShape = new Shape[3];
      arrayOfShape[0] = new Rectangle();
      arrayOfShape[1] = new Triangle();
      arrayOfShape[2] = new Circle();
     }

     public static void drawAll() {
      for (int i = 0; i < arrayOfShape.length; i++) {
       arrayOfShape[i].draw();
      }
     }
    }

    <결과>

     

    #다형성의 특징

    - 부모클래스의 참조변수로 자식의 클래스의 객체를 참조가능.

    - 호출하는 매소드가 자식클래스에서 재정의 되었다면 동적바인딩되서 실제 호출되는 메소드는 자식클래스의 메소드 이다.

    - 순수하게 부모클래스의 영역만 참조가능. (부모클래스에 정의된 멤버에만 접근가능)

     

    실제 참조하는 객체는 Rectangle 이기 때문에 setWidth가 분명 존재함. but, 참조하려면 타입캐스팅(형변환) 해야된다.

    Shape s = new Rectangle();
      ((Rectangle)s).setWidth(10);

    ((Triangle)s).setBase(1); // 코드생성에는 문제가 없으나 런타임 익셉션가 발생!!

    따라서 다음과 같은 코드를 생성하려면

    if(s instanceof Rectangle)
      {
      ((Rectangle)s).setWidth(10);
      }

    검사문을 넣어 확인하여야 된다.

     

    # instanceof 응용하기

     public static double getArea(Shape s) {
      double area = 0;
      if (s instanceof Rectangle) {
       area = ((Rectangle) s).getHeight() * ((Rectangle) s).getWidth();
      } else if (s instanceof Triangle) {
       area = ((Triangle) s).getHeight() * ((Triangle) s).getBase() * 0.5;
      } else if (s instanceof Circle) {
       area = ((Circle) s).getRadius() * ((Circle) s).getRadius() * 3.14;
      }
      return area;
     }

     

    # 자동형변환/강제형변환

    "부모클래스 변수 = 자식클래스타입" 일때, 자동형변환이 일어난다.

    -> 프로그램 실행도중 자동적으로 형변환이 일어나는것으로 위의 조건이 만족할때 형변환일 일어난다.

    반대의 경우로 "자식클래스 변수 = 부모클래스타입" 일 경우 ClassCastException 예외를 발생시킨다.

    위와 같이 자식타입이 부모타입으로 변환된 상태라는 조건을 만족시키며

    자식클래스 변수 = (자식클래스) 부모클래스타입" 일 경우 강제 형변환일 일어난다.







    펌 출처 : http://justbaik.tistory.com/22

    반응형

    '삼성SDS_멀티캠퍼스 > Java' 카테고리의 다른 글

    12일 차 추상클래스, 추상메소드, 상속  (0) 2015.09.22
    12일 차 Inner Class(이너클래스)  (0) 2015.09.22
    11일 차 다형성  (0) 2015.09.21
    10일 차 상속 중간점검  (0) 2015.09.18
    10일 차 상속  (0) 2015.09.18
Designed by Tistory.