본문 바로가기
멘토씨리즈 자바/예제

[응용문제] 다형성과 타입 변환

by Hwanii_ 2023. 5. 22.
728x90

SECTION 11 - 다형성과 타입 변환

300 ~ 301 page.

 

1. 다음 코드는 컴파일 에러가 발생합니다.

컴파일 에러가 발생하는 곳을 모두 찾아 수정해 보세요.

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

class OpenCar extends Car { }
classSportsCar extends OpenCar { }

main()

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

 

=>

 

 

1. SchoolBus 클래스는 Car 클래스보다 하위 클래스 이다. (상속)

따라서, new SchoolBus를 해주던지

클래스명을 Car로 바꿔줘야 한다.

 

ok
ok

 

 

2. Bus 클래스와 객체 OpenCar, SportsCar은 상속의 개념이 아니다. 서로 다른 클래스 이다.

Bus 클래스의 객체로 또는

하위클래스 객체로 바꿔주면 된다.

 

아니면, 클래스명을 Car클래스류로 바꿔준다.

 

ok
ok
ok
ok
ok

 

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

 

부모 클래스에게 상속받은 메서드를 재정의하여 자식 클래스용 메서드를 구현하고

자식 객체를 통해 메서드를 호출할 때는 부모의 메서드가  아니라 자식의 메서드가 호출된다.

 

1) 오버라이딩

2) 오버로딩

3) 오버플로우

 

=> 오버라이딩

 

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

 

1) class Speaker

2) class RedSpeaker

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

// 실행 결과

빨간 스피커가 켜졌습니다.

파란 스피커가 켜졌습니다.

 

=> 추가

 

 

 

반응형

'멘토씨리즈 자바 > 예제' 카테고리의 다른 글

[응용문제] 파일 입출력  (0) 2023.05.28
[응용문제] 스레드  (0) 2023.05.28
[응용문제] 상속  (0) 2023.05.21
[응용문제] 생성자  (0) 2023.05.21
[응용문제] 메서드  (0) 2023.05.21