- 여러 클래스에 공통적으로 사용될 수 있는 추상 클래스를 바로 작성하거나 기존 클래스의 공통 부분을 봅아서 추상 클래스를 만든다 -> 코드의 중복 제거
class Marine{
int x,y;
void move(int x, int y){/* 지정된 위치로이동 */}
void stop(){/* 현재 위치에 정지 */}
void stimPack(){/* 스팀팩을 사용한다 */}
}
class Tank{
int x,y;
void move(int x, int y){/* 지정된 위치로이동 */}
void stop(){/* 현재 위치에 정지 */}
void changeMode(){/* 공격 모드를 변경한다 */}
}
class DropShip{
int x,y;
void move(int x, int y){/* 지정된 위치로이동 */}
void stop(){/* 현재 위치에 정지 */}
void load(){/* 선택된 대상 태운다 */}
void unload(){/* 선택된 대상 내린다 */}
}
위 코드는 추상 클래스를 사용하여 코드의 중복을 아래와 같이 제거할 수 있다.
abstract class Unit{
int x,y;
abstract void move(int x, int y);
void stop(){/* 현재 위치에서 정지*/}
}
class Marine extends Unit{
void move(int x, int y){/* 지정된 위치로이동 */}
void stimPack(){/* 스팀팩을 사용한다 */}
}
class Tank extends Unit {
void move(int x, int y){/* 지정된 위치로이동 */}
void changeMode(){/* 공격 모드를 변경한다 */}
}
class DropShip extends Unit {
void move(int x, int y){/* 지정된 위치로이동 */}
void load(){/* 선택된 대상 태운다 */}
void unload(){/* 선택된 대상 내린다 */}
}
실습
abstract class Unit{
int x,y;
abstract void move(int x, int y);
void stop(){/* 현재 위치에서 정지*/}
}
class Marine extends Unit{
void move(int x, int y){
System.out.println("Marine의 좌표: x= " +x +" y= "+y);
}
void stimPack(){/* 스팀팩을 사용한다 */}
}
class Tank extends Unit {
void move(int x, int y){
System.out.println("Tank의 좌표: x= " +x +" y= "+y);}
void changeMode(){/* 공격 모드를 변경한다 */}
}
class DropShip extends Unit {
void move(int x, int y){
System.out.println("DropShip의 좌표: x= " +x +" y= "+y);
}
void load(){/* 선택된 대상 태운다 */}
void unload(){/* 선택된 대상 내린다 */}
}
public class Main {
public static void main(String[] args) {
Unit [] group = {new Marine(),new Tank(),new DropShip()};
for (Unit unit : group) {
unit.move(100, 200);
}
}
}