자바의 객체 지향 개념에서 중요한 것 중 하나는 다형성이다.
다형성은 이름대로 여러가지 형태를 가질 수 있는 성질을 말해요; 코드로는 부모 참조 변수에 자식 객체를 생성하는 것.
참조값은 부모이며, 실제 저장된 객체는 자식 이라는 뜻.
다형성이 부모 참조 변수에 실제 자식의 인스턴스를 넣는 것. 다형성은 이름 그대로 형태가 여럿인 것을 말한다. 예를들어 자식이 여럿인 클래스가 있다면 어떤 인스턴스도 참조 변수에 할당 할수 있다. 즉 겉 형태는 부모 형태 하나지만, 실제 인스턴스는 어떤 자식 인스턴스일 수도 있다.
부모
class parent{
...
}
class c1 extends Parent{
}
class c2 extends Parent{
}
class c3 extends Parent{
}
Parent p = new c1(); // c1의 인스턴스
Parent p = new c2(); // c2의 인스턴스
Parent p = new c3(); // c2의 인스턴스
예제를 보자
인스턴스 instanceof 클래스 : 인스턴스가 클래스의 인스턴스라면 true반환
package polymorphism;
//instanceof 연산자
class Data1{
void print(){
System.out.println("class Data1 print method");
}
}
class Data2{
void show(){
System.out.println("class data2 show method");
}
}
public class Code2 {
public static void main(String[] args){
Data1 d1 = new Data1();
Data2 d2 = new Data2();
if(d1 instanceof Data1){
d1.print(); // d1의 Data가 1의 인스턴스가 인지 판단한다.
}
열 if(d2 instanceof Data2){
d2.show();
}
}
}
부모가 여러 개의 자식 클래스를 갖는 경우에, 부모 참조 변수에 자식 인스턴스를 넣었을대 어떤 자식 클래스의 인스턴스인지 판단해야 하는 경우가 있다, 이때 instanceof 연산자를 유용하게 쓸수잇다. 그리고 필요에 다라 적절한 형 변환이 필요합니다.
class Parent{
void print(){
System.out.println("Parent: print()" );
}
void show(){
System.out.println("Parent : show()");
}
}
class ChildA extends Parent{
void print(){
System.out.println("Child-A :print() ");
}
void showA(){
System.out.println("Child-A : show()");
}
}
class ChildB extends Parent{
void print(){
System.out.println("Child-B:print()");
}
void showB(){
System.out.println("Child-B : show()");
}
}
public class Code4 {
static void doWork(Parent p){
if(p instanceof ChildA){
ChildA ca = (ChildA) p;
ca.print();
ca.show();
ca.showA();
}else if(p instanceof ChildB){
ChildB cb = (ChildB) p ;
cb.print();
cb.show();
cb.showB();
}else{
p.print();
p.show();
}
}
public static void main(String[] args){
Parent p = new Parent();// 부모의 p이다
doWork(p);
ChildA a = new ChildA();
doWork(a);
ChildB b = new ChildB();
doWork(b);
}
인스턴스가 클래스의 속한 인스턴스가 아니라면 형 변환을 통해 바꿔주어야한다
class Car{
private String color;
Car(){}
Car(String color){this.color=color;}
void drive(){System.out.println("driving...");}
}
class Sedan extends Car{
private int seats;
Sedan(){}
Sedan(String color, int seats){
super(color);
this.seats = seats;
}
void showSeats(){
System.out.println("This car has" + seats +"seats.");
}
}
class Truck extends Car{
private int wheel;
Truck(){}
Truck(String color, int wheel){
super(color);
this.wheel = wheel;
}
void showWheel(){
System.out.println("this truck is" + wheel +"drive truck");
}
}
public class Code3 {
public static void main(String[] args){
Car myCar = new Sedan("white", 4);
Car yourCar = new Truck("blue",4);
if(myCar instanceof Sedan){
myCar.drive(); //클래스 형변환 세단으로 변경 쇼싯트는 카클래스에 없기때문에
}
if(yourCar instanceof Truck){
((Truck)yourCar).showWheel();
}
}
}