๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
FOR SW ENGINEER๐Ÿ‘ฉ‍๐Ÿ’ป/JAVA

JAVA_์ •์  ์ œํ•œ์ž (Static)

by ์”จ๋‹ˆ 2021. 9. 12.
728x90

์‚ฌ์šฉ์ œํ•œ์ž(Usage Level modifier)

Static

- static๋ณ€์ˆ˜๋Š” ๊ฐ์ฒด๊ฐ„ ๊ฐ’์˜ ๊ณต์œ ๋ฅผ ์˜๋ฏธ

- static๋ฉค๋ฒ„๋Š” ๊ฐ์ฒด ์ƒ์„ฑ ์—†์ด ํด๋ž˜์Šค๋ช….์ด๋ฆ„ ์œผ๋กœ ์ฐธ์กฐ ๊ฐ€๋Šฅ

- static๋ฉ”์„œ๋“œ๋Š” ๊ฐ™์€ static๋ฉค๋ฒ„๋งŒ ์ฐธ์กฐ๊ฐ€๋Šฅ.

 

1.์ •์ ์ œํ•œ์ž ํŠน์ง•

- static์ œํ•œ์ž๋Š” ๋ณ€์ˆ˜, ๋ฉ”์„œ๋“œ์— ์ ์šฉ๋˜๋Š” ์ž๋ฐ”์˜ ํ‚ค์›Œ๋“œ

- static๋ฉ”์„œ๋“œ๋‚˜ ๋ณ€์ˆ˜๋Š” ํ•ด๋‹น ํด๋ž˜์Šค ๊ฐ์ฒด ์—†์ด๋„ ์ฐธ์กฐ๊ฐ€๋Šฅ.

- static๋ธ”๋ก(Static ๋ฉ”์„œ๋“œ, ์ •์  ์ดˆ๊ธฐํ™”) ์•ˆ์—๋Š” static๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉํ•ด์•ผํ•˜๊ณ , static๋ฉ”์„œ๋“œ๋งŒ ํ˜ธ์ถœ๊ฐ€๋Šฅ.

- static์ œํ•œ์ž๋Š” ์ง€์ •๋œ ๋ณ€์ˆ˜์™€ ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ์ฒด์™€ ๋ฌด๊ด€ํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ์–ด this๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์—†์Œ.

- static๋ฉ”์„œ๋“œ๋Š” non-static๋ฉ”์„œ๋“œ๋กœ ์žฌ์ •์˜(Overriding) ๋  ์ˆ˜ ์—†์Œ.

- ๋Œ€ํ‘œ์ ์ธ static๋ฉ”์„œ๋“œ๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ main()๋ฉ”์„œ๋“œ์ž„.

 

2. ์ •์ ๋ฉ”์„œ๋“œ(Static method)

- static๋ฉ”์„œ๋“œ๋Š” static๋ณ€์ˆ˜์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ํ•ด๋‹น ํด๋ž˜์Šค์˜ ๊ฐ์ฒด ์ƒ์„ฑ ์—†์ด๋„ ์ฐธ์กฐ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•ด์คŒ.

- static๋ฉ”์„œ๋“œ์—์„œ ๋ฉค๋ฒ„ ์ฐธ์กฐํ•  ๋•Œ ์ฃผ์˜์‚ฌํ•ญ "static๋ฉ”์„œ๋“œ ์•ˆ์—์„œ non-static๋ฉค๋ฒ„๋ฅผ ๊ฐ์ฒด ์ƒ์„ฑ์—†์ด ์ง์ ‘ ์ฐธ์กฐํ•  ์ˆ˜ ์—†์Œ"

 

โ–ถ์ผ๋ฐ˜๋ฉค๋ฒ„๋ณ€์ˆ˜ & static ๋ฉค๋ฒ„๋ณ€์ˆ˜ ์„ ์–ธ

public class Count{
	public int a; // ์ผ๋ฐ˜๋ณ€์ˆ˜ ์„ ์–ธ
   	public static int b; // static๋ฉค๋ฒ„ ๋ณ€์ˆ˜
    
    //static์ด ๋ถ™์œผ๋ฉด ๊ฐ์ฒด ์‚ฌ์ด ๋™์ผํ•œ๊ฐ’ ๊ฐ–์Œ.
}
public class MainClass{ 
	public static void main(String[] args){ //๋Œ€ํ‘œ์ ์ธ static๋ฉ”์„œ๋“œ
    	
        Count c1 = new Count(); //์ฒซ๋ฒˆ์งธ c1 ๋ฉ”์†Œ๋“œ ์ƒ์„ฑ
        c1.a++;
        c1.b++;
        
        System.out.println("c1์˜ a:" + c1.a);
        System.out.println("c1์˜ b:" + c1.b); //c1.a & c1.b ๋ชจ๋‘ 1์ถœ๋ ฅ
        
        Count c2 = new Count(); //๋‘๋ฒˆ์งธ c2 ๋ฉ”์†Œ๋“œ ์ƒ์„ฑ
        c2.a++;
        c2.b++;
        
        System.out.println("c2์˜ a:" + c2.a); // 1
        System.out.println("c2์˜ b:" + c2.b); // 2
        //b๋Š” static๋ณ€์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์—
        //์ƒˆ๋กœ์šด ๋ฉ”์†Œ๋“œ์˜ b์—ฌ๋„ ๊ฐ’์ด ์ดˆ๊ธฐํ™” ๋˜์ง€์•ˆ๊ณ  ์ด์ „์˜ ๊ฐ’์„๊ฐ€์ง€๊ณ  ์žˆ์Œ.
        //๋”ฐ๋ผ์„œ c1.b์˜ b๊ฐ€ 1์˜ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์žˆ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— c2.b++์€ 2๊ฐ€๋จ.
    }
}

 

โ–ถ ์ผ๋ฐ˜๋ฉ”์„œ๋“œ & static๋ฉ”์„œ๋“œ ์„ ์–ธ

 

โ–ถ staticํ™œ์šฉ

 

728x90