Programming Language/Java

자바 final과 static 변수 이해하기

Jaybon 2020. 3. 27. 14:24

final변수는 한번초기화하면 바뀌지 않는 변수를 말한다.
보통 변수이름을 대문자로 적는다.

스타크래프트에서 유닛을 업그레이드하면 이미 있는 유닛뿐만 아니라
새로 생성되는 유닛들도 업그레이드된 채로 생성된다.

static 변수를 이용하여 업그레이드하면 가능.

package stars;

class Zealot {
	final String NAME; // 한번 초기화하면 Read Only , 대문자로 적는 것이 약속
	int hp;
	static int attack = 10;

	public Zealot(String name) {
		this.NAME = name;
		this.hp = 100;
	}

}

class Dragoon {
	final String NAME;
	int hp;
	static int attack = 15;

	public Dragoon(String name) {
		this.NAME = name;
		this.hp = 100;
	}

}

public class GameStart {
	public static void main(String[] args) {
		// 공격력 업그레이드하기
		Zealot.attack++;

		// 질럿 생성하기
		Zealot z1 = new Zealot("1번질럿");
		System.out.println(Zealot.attack);
	}
}