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("스포츠카 지나가요~ 씽~");}
}
2-1 . 배열 초기화
결과물 - 주소값이 나온다( 각 객체가 생성된 메모리 공간의 주소값)
com.study.Ambulance@3b6eb2ec
com.study.Cultivator@1e643faf
com.study.SportsCar@6e8dacdf
2-2. 부모타입의 자식 클래스 객체들로 바로 배열 초기화 하려면 아래와 같이 하면됨!
Car[] cars = {new Ambulance(), new Cultivator(), new SportsCar()};
결과물
앰블런스 지나가요~삐뽀삐뽀~
경운기 지나가요~덜컹덜컹~
스포츠카 지나가요~ 씽~
3-2. 향상된 for문 사용해보기
for(Car obj : cars) obj.run();
결과물 - 동일하다
앰블런스 지나가요~삐뽀삐뽀~
경운기 지나가요~덜컹덜컹~
스포츠카 지나가요~ 씽~
class Person_1{}
class Batman extends Person_1{}
class Human {}
class Superman extends Human{}
즉 아래와 같이 부모 클래스로 객체를 생성했을 때 부모클래스 객체만 배열에 초기화 할 수 있다.
Person_1[] persons = new Person_1[10]; // 이건 Person 전용
persons[0] = new Person_1();
persons[1] = new Person_1();
자식 클래스도 똑같다.
Batman[] batmans = new Batman[10]; // 이건 Batman 전용
batmans[0] = new Batman();
batmans[1] = new Batman();
Human[] humans = new Human[10];
humans[0] = new Humans(); - 이건 당연히 되고
humans[1] = new Superman(); - 자식클래스로도 부모타입으로 받아 객체 생성을 할 수 있다.
결론적으로, Object는 가장 최상위 조상(단군 할아버지,창조주)이므로 어떤 객체를 보내도 그 보다 상위 타입이 된다.
System.out.println(new Person_1());
System.out.println(new Batman());
System.out.println(new Human());
System.out.println(new Superman());
강의가 맥락없이 갑자기 뚝 끊겼다 ㅋㅋㅋ 다형성 개념을 끝으로 oop파트는 끝났다. 자바의 신을 사서 자바 공부를 더 해야 할 것 같다. 그다음 알고리즘 파트 기대되는데 너무 기대하면 안될것 같다.ㅎㅎ