Static ๋ณ์
ํด๋์ค ๋ด์ ๋ชจ๋ ์ธ์คํด์ค๋ค์ด ๊ณต์ ํ๋ฉฐ, ๋ฉ๋ชจ๋ฆฌ์ ํ๋ฒ ํ ๋น๋์ด ํ๋ก๊ทธ๋จ์ด ์ข
๋ฃ๋ ๋ ์์ด์ง๋ค
ํด๋์ค ์ธ๋ถ์์ ์ ๊ทผํ๋ ๋ฒ
1.
ํด๋์ค ์ด๋ฆ์ ํตํ ์ ๊ทผ
2.
์ธ์คํด์ค ์ด๋ฆ์ ํตํ ์ ๊ทผ
๊ณต์ ๋ณ์
Instance ๋ณ์๋ ํด๋น instance์์์๋ง ์ ํจํ์ง๋ง static ๋ณ์๋ ํ๋ฒ ์์ฑ๋๋ฉด ํด๋์ค์ ๋ชจ๋ ์ธ์คํด์ค๋ค์ด ๊ณต์ ํ๋ค
class InstCnt{
static int instNum = 0;
InstCnt(){
instNum++;
}
}
class ClassVar{
public static void main(String[] args){
InstCnt cnt1 = new InstCnt();
InstCnt cnt2 = new InstCnt();
InstCnt cnt3 = new InstCnt();
}
}
Java
๋ณต์ฌ
instNum์ด InstCnt object๊ฐ ์์ฑ๋ ๋๋ง๋ค ์
๋ฐ์ดํธ ๋์ด 3์ด ๋๋ค
ํ์ฉ
์ธ์คํด์ค ๋ณ๋ก ๊ฐ์ง๊ณ ์์ ํ์ ์์ด ๊ฐ์ ์ฐฝ์กฐ๋ ๊ณต์ ๊ฐ ๋ชฉ์ ์ธ ๋ณ์
static final double PI = 3.14;
Java
๋ณต์ฌ
์ธ๋ถ์์๋ ์ฐธ์กฐํ๋ ๊ฐ์ด๋ผ๋ฉด public์ผ๋ก ์ ์ธํ๋ค
Static Method์๋ Instance ๋ณ์๋ฅผ ์ฌ์ฉ ํ ์ ์๋ค
class AAA{
int num = 0;
static void addNum(int n) {
num += n; ---> error
}
}
Java
๋ณต์ฌ
Static method๋ ๊ฐ์ฒด๊ฐ ์์ฑ๋์ง ์์๋ ์ฌ์ฉํ ์ ์๋๋ฐ, num ๋ณ์๋ ๊ฐ์ฒด๊ฐ ์์ฑ๋๊ธฐ ์ ์๋ ๋ฉ๋ชจ๋ฆฌ์ ์กด์ฌํ์ง ์๋๋ค
Static ํจ์
System.out.println();
public static void main(String[] args)
public ๋ชจ๋ ํด๋์ค๊ฐ ์ ๊ทผํ ์ ์๋๋ก
dtatic ์ธ์คํด์ค ์์ฑ๊ณผ ๊ด๊ณ์์ด ๊ฐ์ฅ ๋จผ์ ํธ์ถ ๋๋๋ก
์์ธ ์ฒ๋ฆฌ
Try and Catch
try์์ ๋ช
๋ น์ ์ค๋ฅ๊ฐ ๋๋ฉด catch ์์ ๋ช
๋ น์ ์คํํ๋ค
๋ฌธ๋ฒ ์ค๋ฅ๊ฐ ์๋ runtime์ ๋ฐ์ํ๋ ์ค๋ฅ๋ฅผ ๋ค๋ฃฐ ์ ์๋ค
try {
int x = 0/ 0;
System.out.println("ํธ๋ผ์ด ์");
} catch (Exception e) {
System.out.println("์บ์น ์");
} finally {
System.out.println("๋ฌด์กฐ๊ฑด ์คํ");
}
Java
๋ณต์ฌ
output:
์บ์น ์
๋ฌด์กฐ๊ฑด ์คํ
0/0์์ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ฉด catch๋ก ๋์ด๊ฐ๋ค
Finally
try๋ catch๊ฐ ์ค ์ด๋ค ๊ฒ์ด ์คํ๋๋๋ผ๋ ๋ฌด์กฐ๊ฑด ์คํ๋๋ค
Exception
๋ชจ๋ exception์ ๋ถ๋ชจ ํด๋์ค
ArithmeticException
์ฐ์ฐ์ค๋ฅ
ํ์ง๋ง ArithmaticException๊ณผ Exception์ด ์์๊ด๊ณ์ ์๊ธฐ ๋๋ฌธ์ Exception๋ง ์์ด๋ ์ค๋ฅ๋ฅผ ์ก์ ์ ์๋ค.
InputMismatchException
Exception e๋ก๋ int๋ฅผ ์
๋ ฅํด์ผ ํ ๋ string์ ์
๋ ฅํ๋ฉด ๋ฐ์ํ๋ ์ค๋ฅ๋ฅผ ์ก์ ์ ์๋ค
Throws
JVM์๊ฒ Exception์ ๋์ง๊ฒ ๋ค
ํจ์์ parameter๊ฐ ๋ค์ด๊ฐ๋ ๊ฐ๋ก ์์ ๋ฌ์์ค๋ค
public static void main(String[] args) throws IOException
Java
๋ณต์ฌ
IOException
file์ ์ฝ์ผ๋ ค๋ฉด ํ์ํ๋ค
์ฌ๋ฌ๊ฐ์ exception์ throwํ๊ณ ์ถ์ผ๋ฉด
public void method() throws IOException, InputMismatchException {}
์์ธ ํด๋์ค ๊ตฌ๋ถ
Checked Exception ๊ฐ๋ฐ์๊ฐ ์ฒ๋ฆฌ์ผํด ํ๋ ์ค๋ฅ
Catch ์ ์ค๋ฅ ๋ค๋ฃจ๋ ๋ช ๋ น์ด:
System.out.println(e.getMessage()); ์ค๋ฅ์ ์ด์ ๋ฅผ ์ถ๋ ฅ
e.printStackTrace(); ๊ฐ๋ฐ์๊ฐ ์ค๋ฅ๋ฅผ trackํ ์ ์์