다형성(polymorphism)은 "많은(poly) + 모양(morph)"이라는 의미로서 주로 프로그래밍 언어에서 하나의 식별자로 다양한 타입(클래스)을 처리하는 것을 의미한다. 즉, 똑같은 명령을 내리지만 객체의 타입이 다르면 서로 다른 결과를 얻을 수 있는 것이 다형성이다. 객체 지향 기법에서 하나의 코드로 다양한 타입의 객체를 처리하는 중요한 기술이다 = 동일한 코드로 다양한 타입의 객체를 처리할 수 있는 기법이다.
상속과 다형성
다형성은 상속을 통하여 구현된다. 예를 들어보자
class Shape {
protected int x, y;
public void draw() {
System.out.println("Shape Draw");
}
} // 각 도형들을 2차원 공간에서 도형의 위치를 나타내는 기준점 (x, y)를 가진다. 이것은 모든 도형에 공통적인 속성이므로 부모 클래스인 Shape에 저장한다.
class Rectangle extends Shpae {
private int width, height;
public void draw() {
System.out.println("Rectangle Draw");
}
} // Shape에서 상속받아서 사각형을 나타내는 클래스 Rectangle 을 정의하여 보자. Rectangle은 추가적으로 width와 height 변수를 가진다.
class Triangle extends Shape {
private int base , height;
public void draw() {
System.out.println("Triangle Draw");
}
}
class Circle extends Shape {
private int radius;
public void draw () {
System.out.println("Circle Draw");
}
}
----- 출력 1번째 모습 -----------
public class ShapeTest {
public static void main(String[] arg) {
Shape s1, s2;
s1 = new Shape();
s2 = new Rectangle();
// 얼핏보기에는 s2가 오류날것같지만 아니다. 왜냐하면 자식 클래스 객체 안에는 부모 클래스 부분이 있기 때문에, 부모 클래스 객체처럼 취급될 수 있다. 즉 부모 클래스 참조 변수로 자식클래스 객체를 참조할 수 있다. 이것을 상향 형변환이라고 한다.
}
}
----- 출력 2번째 모습 -----------
public class ShapeTest {
public static void main(String[] arg) {
Shape s = new Rectangle();
Rectangle r = new Rectangle();
s.x = 0;
s.y = 0; // Shape 클래스의 필드와 메소드에 접근하는 것은 OK
s.width = 100;
s.height = 100; // 컴파일 오류가 발생한다. s를 통해서 Rectangle 클래스의 필드와 메소드에 접근할 수 없다.
}
}
출력 값 :
width cannot be resolved or is not a field
height cannot be resolved or is not a field
----- 출력 3번째 모습 -----------
public class ShapeTest {
public static void main(String[] arg) {
Shape arrayOfShapes[] = new Shape[3];
arrayOfShapes[0] = new Rectangle();
arrayOfShapes[1] = new Triangle();
arrayOfShapes[2] = new Circle();
for(int i = 0; i< arrayOfShapes.length; i++) {
arrayOfShapes[i].draw();
}
}
}
출력 값 :
Rectangle Draw
Triangle Draw
Circle Draw
'java > 객체지향 프로그래밍' 카테고리의 다른 글
자바 인터페이스(interface) (0) | 2019.04.16 |
---|---|
자바 실제 객체 (0) | 2019.04.16 |
자바 추상클래스 (0) | 2019.04.16 |
자바 객체 소멸 (0) | 2019.04.11 |
자바 객체 지향 프로그래밍의 특징 (0) | 2019.04.09 |