다형성(Polymorphism)
하나의 오브젝트와 메써드가 다양한 형태를 가질 수 있는 성질을 말한다.
프로그램에서 사용되는 각 요소들은 여러가지 자료형으로 표현될 수 있는데 이를 다형성이라고 한다.
한가지 요소는 한가지의 형태로만 매칭된다는 것이 단형성이고, 하나의 요소가 여러형태로 매칭되는 것을 다형성이라고 하는데 OOP에서는 매우 중요한 개념이다.
최상위 객체인 Object로 다른 객체를 만들 수 있는것도 바로 다형성 때문에 가능한 것이다. 여기서 사용되는 연산자는 instanceof이다. 하나의 객체와 메써드가 다양한 형태를 가질 수 있는 성질
서브 클래스의 객체를 슈퍼클래스의 객체에 대입하거나, 서브 클래스의 객체를 슈퍼 클래스의 객체로 생성하거나, 자료형을 변경할 수 있는 것들도 다형성이다. 부모 클래스 타입의 참조 변수로 자식 클래스 타입의 객체를 참조할 수 있게 되는 것도 다형성이다. 부모가 자식의 오버라이딩 된 기능을 사용하게 하는 것 등도 다형성으로 볼 수 있다.
package java13;
class A {
void methodA() {
System.out.println("method_A");
}
}
class B extends A {
void methodA() { // method() 오버라이딩, 다형성
System.out.println("method_B");
}
void methodC() {
System.out.println("method_C");
}
}
public class Test11 {
public static void main(String[] args) {
A a=new B(); // 다형성
a.methodA();
// a.methodC(); # 오류!! Class C에서 methodA()를 오버라이딩하지 않았다.
}
}

package java13;
abstract class Calc2 { // 추상 클래스
int a ;
int b ;
abstract int result() ; // 추상 메써드
void printResult() {
System.out.println(result()) ;
}
void setData(int m, int n) {
a = m ;
b = n ;
}
}
class Plus extends Calc2 {
int result() { // result() 메서드 오버라이딩, 다형성
return a + b ;
}
}
class Minus extends Calc2 {
int result() {
return a - b ;
}
}
public class Test12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 54, y = 12 ;
Calc2 calc1 = new Plus() ;
Calc2 calc2 = new Minus() ;
calc1.setData(x, y) ;
calc2.setData(x, y) ;
System.out.print(x + " + " + y + " = ") ;
calc1.printResult( ) ;
System.out.print(x + " + " + y + " = ") ;
calc2.printResult( ) ;
}
}

package java13;
class AB {
int methodA(int a, int b) {
return a+b;
}
}
class BC extends AB {
int methodA(int a, int b) {
return a-b;
}
void methodB() {
System.out.println("hi");
}
}
public class Test13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a, b;
a= 20;
b= 10;
AB obj1 = new BC(); // 다형성
System.out.println(obj1.methodA(a,b));
BC obj2 = new BC();
System.out.println(obj2.methodA(a,b));
AB obj3 = new AB();
System.out.println(obj3.methodA(a,b));
}
}

'JAVA' 카테고리의 다른 글
| [JAVA] IO(Input/Output) (0) | 2022.08.03 |
|---|---|
| [JAVA] 제네릭(Generic) (0) | 2022.08.03 |
| [JAVA] Lamda식 (0) | 2022.08.03 |
| [JAVA]collections, set/list/map인터페이스 (0) | 2022.08.03 |
| [JAVA] ArrayList (0) | 2022.08.03 |
댓글