๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] final ์˜ˆ์•ฝ์–ด

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 20.
๋ฐ˜์‘ํ˜•

โ–ถ ์ƒ์ˆ˜๋ฅผ ์˜๋ฏธํ•˜๋Š” final ๋ณ€์ˆ˜

package finalex;

public class Constant {

	int num = 10;
	final int NUM = 100;

	public static void main(String[] args) {

		Constant cons = new Constant();
		cons.num = 50;
		cons.NUM = 200;

		System.out.println(cons.num);
		System.out.println(cons.NUM);
	}
    
}

-์ƒ์ˆ˜๋กœ ์„ ์–ธํ•œ NUM์—๋Š” ๋‹ค๋ฅธ ๊ฐ’์„ ๋Œ€์ž…ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

 

 

 

โ–ถ ์—ฌ๋Ÿฌ ์ž๋ฐ” ํŒŒ์ผ์—์„œ ๊ณต์œ ํ•˜๋Š” ์ƒ์ˆ˜ ๊ฐ’ ์ •์˜ํ•˜๊ธฐ

์—ฌ๋Ÿฌ ํŒŒ์ผ์—์„œ ๊ณต์œ ํ•ด์•ผ ํ•˜๋Š” ์ƒ์ˆ˜ ๊ฐ’์€ ํ•œ ํŒŒ์ผ์— ๋ชจ์•„ public static final๋กœ ์„ ์–ธํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค.

package finalex;

public class Define {

	public static final int MIN = 1;
	public static final int MAX = 99999;

	public static final int ENG = 1001;
	public static final int MATH = 2001;

	public static final double PI = 3.14;
	public static final String GOOD_MORNING = "Good Morning!";
}

-๋ชจ๋“  ์ƒ์ˆ˜๋ฅผ static์œผ๋กœ ์„ ์–ธํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ๊ณผ ๊ด€๊ณ„์—†์ด ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

package finalex;

public class UsingDefine {
	public static void main(String[] args) {

		System.out.println(Define.GOOD_MORNING);  // static ์œผ๋กœ ์„ ์–ธ๋˜์—ˆ์œผ๋ฏ€๋กœ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์ง€์•Š๊ณ  ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ์ฐธ์กฐ ๊ฐ€๋Šฅ
		System.out.println("์ตœ์†Ÿ๊ฐ’์€ " + Define.MIN + "์ž…๋‹ˆ๋‹ค.");
		System.out.println("์ตœ๋Œ“๊ฐ’์€ " + Define.MAX + "์ž…๋‹ˆ๋‹ค.");
		System.out.println("์ˆ˜ํ•™ ๊ณผ๋ชฉ ์ฝ”๋“œ ๊ฐ’์€ " + Define.MATH + "์ž…๋‹ˆ๋‹ค.");
		System.out.println("์˜์–ด ๊ณผ๋ชฉ ์ฝ”๋“œ ๊ฐ’์€ " + Define.ENG + "์ž…๋‹ˆ๋‹ค.");
	}

}

<์‹คํ–‰ ๊ฒฐ๊ณผ>

 

 

 

โ–ถ ์ƒ์†ํ•  ์ˆ˜ ์—†๋Š” final ํด๋ž˜์Šค

๋ณด์•ˆ๊ณผ ๊ด€๋ จ๋˜์–ด ์žˆ๊ฑฐ๋‚˜ ๊ธฐ๋ฐ˜ ํด๋ž˜์Šค๊ฐ€ ๋ณ€ํ•˜๋ฉด ์•ˆ ๋˜๋Š” ๊ฒฝ์šฐ์—๋Š” ํด๋ž˜์Šค๋ฅผ final๋กœ ์„ ์–ธํ•œ๋‹ค.

โ€‹

โ€‹

โ˜…tipโ˜…

ํ”„๋กœ๊ทธ๋žจ์„ ์ž˜ ๊ตฌํ˜„ํ•˜๋ ค๋ฉด ํ”„๋กœ๊ทธ๋žจ์„ ๊ฑฐ๊พธ๋กœ ์ง„ํ–‰ํ•ด ๋ณผ ๊ฒƒ !

ex) ์ตœ์ข… ์‹คํ–‰(์ถœ๋ ฅ) ํŒŒ์ผ๋ถ€ํ„ฐ ๋งŒ๋“ค์–ด๋ณด๊ธฐ

์ด๋ ‡๊ฒŒ...

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€