📕 멘토씨리즈 자바

Section11 다형성과 타입 변환 - 응용문제

harveydent 2023. 5. 25. 11:28
728x90

Section11 다형성과 타입

1. 다음 코드는 컴파일 에러가 발생합니다. 컴파일 에러가 발생하는 곳을 모두 찾아 수정해 보세요.

package section11;

class Car {}
class Bus extends Car {}
class SchoolBus extends Bus {}

class OpenCar extends Car {}
class SportsCar extends OpenCar {}

public class PRACTICE_11_01 {
	public static void main(String[] args) {
    	Car c1 = new SchoolBus();
        Bus b1 = new Bus();
        SchoolBus sb = new Car();
        
        Car c2 = new OpenCar();
        OpenCar oc = new SportsCar();
        Bus b3 = new OpenCar();
        Bus b4 = new SportCar();
    }
}
더보기
package section11;

class Car {}
class Bus extends Car {}
class SchoolBus extends Bus {}

class OpenCar extends Car {}
class SportsCar extends OpenCar {}

public class PRACTICE_11_01 {
	public static void main(String[] args) {
    	Car c1 = new SchoolBus();
        Bus b1 = new Bus();
//      SchoolBus sb = new Car(); // error
        SchoolBus sb = new SchoolBus();
        Car c = new Car();
        
        Car c2 = new OpenCar();
        OpenCar oc = new SportsCar();
//      Bus b3 = new OpenCar(); // error
//      Bus b4 = new SportCar(); // error
    }
}

2. 다음 설명에 해당하는 용어는 무엇입니까?

부모 클래스에게 상속받은 메서드를 재정의하여 자식 클래스용 메서드를 구현하고 자식 객체를 통해 메서드를 호출할 때는 부모의 메서드가 아니라 자식의 메서드가 호출된다.
  1. 오버라이딩
  2. 오버로딩
  3. 오버플로우
더보기
  1. 오버라이딩
    • O
  2. 오버로딩
    • X
  3. 오버플로우
    • X

3. 다음과 같은 결과가 나오도록 아래 클래스를 구현해 주세요.

  • class Speaker
  • class RedSpeaker
  • class BlueSpeaker
package section11;

class Person {
	Speaker speaker;
    
    Person(Speaker speaker) {
    	this.speaker = speaker;
    }
    
    void turnOn() {
    	System.out.println(speaker.getName() + "이 켜졌습니다.");
    }
}

public class PRACTICE_11_03 {
	public static void main(String[] args) {
    	Speaker s1 = new RedSpeaker();
        Person p1 = new Person(s1);
        p1.turnOn();
        
        Speaker s2 = new BlueSpeaker();
        Person p2 = new Person(s2);
        p2.turnOn();
    }
}
빨간 스피커가 켜졌습니다.
파란 스피커가 켜졌습니다.
더보기
package section11;

class Person {
	Speaker speaker;
    
    Person(Speaker speaker) {
    	this.speaker = speaker;
    }
    
    void turnOn() {
    	System.out.println(speaker.getName() + "이 켜졌습니다.");
    }
}

class Speaker {
}
class RedSpeaker {
}
class BlueSpeaker {
}

public class PRACTICE_11_03 {
	public static void main(String[] args) {
    	Speaker s1 = new RedSpeaker();
        Person p1 = new Person(s1);
        p1.turnOn();
        
        Speaker s2 = new BlueSpeaker();
        Person p2 = new Person(s2);
        p2.turnOn();
    }
}
728x90