5장 상속(계속)
이전 시간 실습
http://jylecture.blogspot.kr/2016/04/java-44-5.html누군가의 실습 내용:
https://github.com/amdjd/JavaExercise/blob/110d54c2e5d0ccbe184ee9a57bef1ddcf4b11e41/src/classes/Lake.javamoveFish() 함수
public void moveFish() {for (int i = 0; i < fish.length; i += 2) {
fish[i].move(width, height);
}
for (int i = 1; i < fish.length; i += 2) {
fish[i].move2(width, height);
}
}
상속을 이용해서 바꿔보기
https://github.com/jyheo/JavaExercise/blob/master/src/classes/Lake10.javaclass FoolFish extends Fish { // 상속
FoolFish(String name, String shape) {
super(name, shape); // 부모 클래스의 생성자를 부름, super는 부모 클래스를 가리킴
}
public void move(int width, int height) { // 메소드 오버라이딩(overriding), 원래 메소드는?
x++; // Fish의 x, y가 private int였다고 지금은 protected int로 바뀌어 있음. 왜?
y++;
if (x >= width)
x = 0;
if (y >= height)
y = 0;
}
}
public class Lake10 {
private int width;
private int height;
private Fish[] fishes;
public Lake10(int width, int height) {
this.width = width;
this.height = height;
fishes = new Fish[10];
for (int i = 0; i < fishes.length; i++) {
if (i % 2 == 0)
fishes[i] = new Fish("Even", "<#--<");
else
fishes[i] = new FoolFish("Odd", "<$--<"); // Fish 레퍼런스가 FoolFish를 가리킨다?
// 업 캐스팅(upcasting)
}
}
public void moveFish() {
for (Fish f : fishes) // f가 Fish 객체일 때도 있고, FoolFish일 때도 있는데,
f.move(width, height); // move()는 누구의 move()가 불리는가?
} // 동적 바인딩(dynamic binding)