다형성,instanceof ,형변환

이영광·2022년 1월 30일

자바

목록 보기
1/34

자바의 객체 지향 개념에서 중요한 것 중 하나는 다형성이다.

다형성은 이름대로 여러가지 형태를 가질 수 있는 성질을 말해요; 코드로는 부모 참조 변수에 자식 객체를 생성하는 것.

참조값은 부모이며, 실제 저장된 객체는 자식 이라는 뜻.

다형성의 이해

다형성이 부모 참조 변수에 실제 자식의 인스턴스를 넣는 것. 다형성은 이름 그대로 형태가 여럿인 것을 말한다. 예를들어 자식이 여럿인 클래스가 있다면 어떤 인스턴스도 참조 변수에 할당 할수 있다. 즉 겉 형태는 부모 형태 하나지만, 실제 인스턴스는 어떤 자식 인스턴스일 수도 있다.

부모
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

  • 어느 인스턴스가 어느 클래스의 인스턴스인지를 판단해야 할때가 있는데
    이대 instanceof 연산자를 사용하며

예제를 보자

인스턴스 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();
       }

    }
}

profile
《REACT》《JAVASCRIPT 》 만지고있어욤

0개의 댓글