/ JAVAJUNGSUK

Ch7-33~34. 추상 클래스 작성

자바의 정석 기초편

0. 목차



Chapter7. 객체지향 프로그래밍Ⅱ

Ch7 - 33. 추상 클래스의 작성

Ch7 - 34. 추상 클래스의 작성 예제



Ch7 - 33. 추상 클래스의 작성


▶ 추상 클래스 작성 방법

▷ 여러 클래스에 공통적으로 사용될 수 있는 추상 클래스를
▷ 바로 작성하거나
▷ 기존 클래스의 공통 부분을 뽑아서 추상 클래스를 생성


▶ 추상 클래스의 장점

▷ 추상화 ↔ 구체화
▷ 불명확 ↔ 명확
▷ 때론 불명확하고 애매한 게 장점일 때가 있음
▷ 추상화 된 코드 : 유연성↑, 변경에 유리
GregofianCalendar cal = new GregofianCal(); // 구체적
Calendar cal = Calendar.getInstance(); // 추상적, Calendar는 추상 클래스



Ch7 - 34. 추상 클래스의 작성 예제


▶ 공통 부분 추상 클래스로 작성

abstract class Unit {
	int x, y;
	abstract void move(int x, int y);
	void stop() { }
}

class Marine extends Unit {
Marine() { }

	void move(int x, int y) { System.out.printf("Marine [%d, %d] move\n", x, y); }
	void stimPack() { }
}

class Tank extends Unit {
Tank() { }

	void move(int x, int y) { System.out.printf("Tank [%d, %d] move\n", x, y); }
	void changeMode() { }
}

class Dropship extends Unit {
Dropship() { }

	void move(int x, int y) { System.out.printf("Dropship [%d, %d] move\n", x, y); }
	void load() { }
	void unload() { }
}

class Test {
Test() { }

	public static void main(String[] args) {
		Unit[] group = { new Marine(), new Marine(), new Dropship() };
		
		for (int i = 0; i < group.length; i++) {
			group[i].move(100, 200);
		}
	}
}

// console
Marine [100, 200] move
Marine [100, 200] move
Dropship [100, 200] move