본문 바로가기

Zero Base 백엔드 스쿨 6기

B BE 6th - 자바 공부 #7-1 상속-다형성 + 문제

1.
[다형성] : 한 객체가 여러 가지 타입을 가질 수 있는 것.


부모 클래스 타입의 참조 변수로 자식클래스 인스턴스 참조.
EX)
class Person{}
class Student extends Person {}

Person p1 = new Student ();    // 가능
Student s1 = new Person ();    // 불가능  : 부모에서 나오지만 자식의 형태는 불가.

클래스명1 변수명 = new 클래스명2 
변수명.메소드

 

클래스2에 선언된 메소드로 출력되지만 해당 메소드는 클래스1과 동일한 메소드여야만 한다.

 

[불가항목] 
1. 부모로부터 출력되지만 자식타입의 형태. 
2. 같은 부모를 상속했어도 자식끼리 호출 

코드 사용 예시 ))
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) {

        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(); 

 

>> 

== 다형성 ==
Person.print
Student.print
Student.print2
Student.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; (불가)  // 부모 = 자식 ok, 자식 = 부모 x
        ss1 = pp3 (불가) // pp3는 Person 클래스 타입이지만 실제로는 Student 클래스에서 호출되므로 업캐스팅임.

                                      고로 ss1 = (Student) pp3  다운캐스팅으로 가능.

        ss1 = (Student) pp3; // 다운 캐스팅 // 역시 자식끼리도 업/다운 캐스팅 안됨.

3.
[instanceof] : 실제 참조하고 있는 인스턴스의 타입 확인, 다형성을 쓸수있는지 없는지를 확인할 수 있음.
부모 to 자식 : 다형성 불가, 자식 to 부모 : 다형성 가능.

코드 사용 예시
System.out.println(변수명 instanceof 클래스명);

Ex) 
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);
        System.out.println(pe1 instanceof Student);

        System.out.println(st1 instanceof Student);
        System.out.println(st1 instanceof Person);

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

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

        if (pe1 instanceof Student) {
            Student stu1 = (Student) pe1;
        }
        if (st1 instanceof Person) {
            Person per1 = (Person) st1;
        }



[[[[[[문제]]]]]]]]]]]]]]]]]]]]]]
//아래의 클래스와 상속 관계에서 다형성을 이용하여
//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 c1 = new Car() ;
        FireTruck f1 = new FireTruck();
        Ambulance am1 = new Ambulance();

        c1.horn();
        f1.horn();
        am1.horn();

 

 

== 실제 사용 코드 형식 ==

class 클래스명1 { 
클래스명1 () {}

public void 메소드명1() {
sout("대사");
 }
}

class 클래스명2 extends 클래스명1 {
public void 메소드명2() {
sout("대사");
 }
}

-메인 클래스-
public class 클래스명3 {
psvm {

클래스명1 변수명1 = new 클래스명1
변수명1.메소드명1;

클래스명2.변수명2 = new 클래스명1
변수명2.메소드명2;