예제로 공부하는 Java 100 문제풀이 Part.4
abstract class Car{
abstract void run();
}
class Ambulance extends Car{
void run() {
System.out.println("엠뷸런스 지나가요 삐뽀삐뽀");
}
}
class Cultivator extends Car{
void run() {
System.out.println("경운기 지나가요 덜컹덜컹");
}
}
class SportsCar extends Car{
void run() {
System.out.println("스포츠카 지나가요 씽~");
}
}
public class Java100_Ex40 {
public static void main(String[] args) {
// [1]: 배열 길이가 3인 Car 객체 배열 선언
// Car[] cars = new Car[3];
// System.out.println(cars[0]); // null --> 각 배열에는 아직 null값만 존재.
//
// //cars 배열 초기화
// cars = new Car[] {new Ambulance(), new Cultivator(), new SportsCar()};
// System.out.println(cars[0]);
// System.out.println(cars[1]);
// System.out.println(cars[2]);
// [2]: 1번 방법 말고 자식 클래스로 객체 생성 --> 타입은 부모 타입으로
// 이렇게 생성된 객체들로 바로 배열 초기화 --> 다형성
Car[] cars = {new Ambulance(), new Cultivator(), new SportsCar()};
// [3]: 반복문 돌면서 각 객체의 run() 메서드 호출
for(int i = 0; i < cars.length; i++) {
// System.out.println(cars[i]); 주소값 출력
cars[i].run();
}
// [4]: 향상된 for문
System.out.println("----------------------------");
for(Car obj:cars) {
// System.out.println(obj); 주소값 출력
obj.run();
}
}
}
'Backend > Java' 카테고리의 다른 글
[인프런] 정수, 배열, 최댓값, 알고리즘 (0) | 2022.03.14 |
---|---|
[인프런] 다형성, 객체 생성, 배열, 반복문 (0) | 2022.03.14 |
[인프런] 추상 클래스, 상속, class (1) | 2022.03.14 |
[인프런] 다형성, 클래스, 호출 (0) | 2022.03.13 |
[인프런] 객체, 생성 방법, 객체 생성 (1) | 2022.03.13 |