[JAVA] 다형성

XXXX·2024년 1월 9일
0
post-thumbnail

다형성

  • 한 객체가 여러 가지 타입을 가질 수 있는 것
  • 부모클래스 타입의 참조 변수로 자식클래스 인스턴스 참조
class Person {}
class Student extends Person {} // 자식 클래스

Person p1 = new Student(); // 자식 클래스에 객체를 만들어 할당
// Student s1 = new Person(); - 불가능.

instanceof

  • 실제 참조하고 있는 인스턴스의 타입 확인
class Person {}
class Student extends Person {}

Person p1 = new Student();
// Student s1 = new Person();
System.out.println(p1 instanceof Person);
// 출력으로 써주면, p1이 Person의 객체인지 아닌지 확인 가능


// Java 프로그래밍 - 다형성

class Person {
    public void print() {
        System.out.println("Person.print");
    }
}

class Student extends Person {
    public void print() {
        System.out.println("Student.print");
    }

    public void print2() {
        System.out.println("Student.print2");
    }
}

class CollegeStudent extends Person {
    public void print() {
        System.out.println("CollegeStudent.print");
    }
}


public class Main {

    public static void main(String[] args) {

//      1. 다형성
        System.out.println("== 다형성 ==");
        Person p1 = new Person();
        Student s1 = new Student();

        Person p2 = new Student();
//        Student s2 = new Person();

        p1.print();
        s1.print();
        s1.print2();
        p2.print();
//        p2.print2();
//        Person이 알고 있는 print() 까지만 접근이 가능하고, print2는 없는 것으로 알고 있음

        Person p3 = new CollegeStudent();
//        CollegeStudent c1 = new Student();
        p3.print();



//      2. 타입 변환
        System.out.println("== 타입 변환 ==");
        Person pp1 = null;
        Student ss1 = null;

        Person pp2 = new Person();
        Student ss2 = new Student();
        Person pp3 = new Student(); // 업캐스팅, 자기 객체가 부모 클래스의 객체로 ..

        pp1 = pp2;
        pp1 = ss2;

        ss1 = ss2;
//        ss1 = pp2;
        ss1 = (Student)pp3; // 다운 캐스팅, 다시 자신의 클래스 쪽으로 타입 변환

//        CollegeStudent cc1;
//        CollegeStudent cc2 = new CollegeStudent();
//        ss1 = (Student) cc2;  - 안됨.
//        cc1 = (CollegeStudent) ss2;   - 안됨.



//      3. instanceof
        System.out.println("== instanceof ==");
        Person pe1 = new Person();
        Student st1 = new Student();
        Person pe2 = new Student();
        Person pe3 = new CollegeStudent();

        System.out.println(pe1 instanceof  Person); // True
        System.out.println(pe1 instanceof  Student); // False

        System.out.println(st1 instanceof Student); // True
        System.out.println(st1 instanceof Person); // True - 부모클래스를 상속받아 만든 객체이기 때문

        System.out.println(pe2 instanceof Person); // True
        System.out.println(pe2 instanceof Student); // True

        System.out.println(pe3 instanceof Person); // True
        System.out.println(pe3 instanceof CollegeStudent); // True

        if (pe1 instanceof Student) {
            Student stu1 = (Student) pe1; // 미리 검사해보고, 형변환.
        }

        if (st1 instanceof Person) {
            Person per1 = (Person) st1;
        }



    }
}

// Practice
// 아래의 클래스와 상속 관계에서 다형성을 이용하여
// Car 객체를 통해 아래와 같이 출력될 수 있도록 Test code 부분을 구현해보세요.
// 빵빵!
// 위이잉!
// 삐뽀삐뽀!

class Car {
    Car(){}
    public void horn() {
        System.out.println("빵빵!");
    }
}

class FireTruck extends Car {
    public void horn() {
        System.out.println("위이잉!");
    }
}

class Ambulance extends Car {
    public void horn() {
        System.out.println("삐뽀삐뽀!");
    }
}

public class Practice {
    public static void main(String[] args) {
        // Test code
        Car car = new Car();
        Car car2 = new FireTruck();
        Car car3 = new Ambulance();

        car.horn();
        car2.horn();
        car3.horn();

//        정답 코드
//        Car car = new Car();
//        car.horn();
//
//        car = new FireTruck();
//        car.horn();
//
//        car = new Ambulance();
//        car.horn();
//
//        Car car2[] = {new Car(), new FireTruck(), new Ambulance()};
//
//        for (Car item: car2) {
//            item.horn();
//        }

    }
}

0개의 댓글