다형성이란 상위 클래스의 타입의 참조변수로 하위클래스의 객체를 참조하는 것을 말한다.

※ 추상클래스나 인터페이스도 상위클래스에 해당한다. 추상클래스를 상속한 클래스의 객체나 인터페이스를 구현한 클래스의 객체를 상위 추상클래스 형이나 인터페이스 형 변수로 참조 가능하다.

abstract public class Unit {
	public int hp;
}

public class Tank extends Unit{
	public String name;
	public Tank() {
		System.out.println("탱크 생성");
	}
}

public class Marine extends Unit{
	public int grade;
	public Marine() {
		System.out.println("마린 생성");
	}
}

public class Game {
	// 매개변수 다형성 활용
	public void destroyUnit(Unit unit) {
		unit.hp = 0;
		unit = null;
		System.out.println("유닛 소멸");
	}
}

public class MainTest {
	public static void main(String[] args) {
		Tank t = new Tank(); // 다형성
		Game game = new Game();
		game.destroyUnit(t);
		Marine m = new Marine();
		game.destroyUnit(m);
		
		// 다형성 활용의 다른 예 
		List<String> list = null;
		list = new ArrayList<String>();
	}
}

+ Recent posts