[JAVA] this๋?
in Tech-Stack on JAVA
Contents
this ๋?
์ธ์คํด์ค์ ์๊ธฐ ์์ ์ ์๋ฏธํ๋ค.
- ์๊ธฐ ์์ ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ฐ๋ฅดํจ๋ค.
- ์ธ์คํด์ค ์์ ์ ์ฃผ์๋ฅผ ๋ฐํํ ๋ ์ฌ์ฉํ๋ค.
- ๋ณ์๋ฅผ ๋ช ์ํ๊ธฐ ์ํด ์ฌ์ฉํ๋ค.
static์ ์ ์ธํ ๋ฉ์๋๋ ๋ชจ๋ this๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
3. ๋ณ์๋ฅผ ๋ช ์ํ ๊ฒฝ์ฐ
class Num {
private int x;
public void setX(int x) {
x = x;
}
}
public static void main(String[] args) {
Num n = new Num();
n.setX(10);
}
setX ๋ฉ์๋์ฒ๋ผ ์ธ์์ ๋ณ์์ ์ด๋ฆ์ด ๊ฐ์ ๊ฒฝ์ฐ(x = x;)์๋ ํผ๋์ด ์๊ธธ ์ ์๋ค.
๊ทธ๋์ this ํค์๋๋ฅผ ํตํด ์ธ์์ ๋ณ์๋ฅผ ๊ตฌ๋ถํ๋ค.
class Num {
private int x;
public void setX(int x) {
this.x = x;
}
}
public static void main(String[] args) {
Num n = new Num();
n.setX(10);
}
this() ๋?
์์ฑ์์์ ๋ค๋ฅธ ์์ฑ์๋ฅผ ํธ์ถํ ๊ฒฝ์ฐ ์ฌ์ฉํ๋ค.
์์ฑ์ ์์์๋ง ํธ์ถ์ด ๊ฐ๋ฅํ๋ค.
class Test() {
private String n;
private int a;
Test() {
// Test ํด๋์ค์ ์์ฑ์ ์ค์ ๋งค๊ฐ๋ณ์๋ก int๋ฅผ ๋ฐ๋ ์์ฑ์๋ฅผ ํธ์ถํ๋ค.
this(9);
System.out.println("default constructor");
}
Test(int a) {
this.a = a;
this("hi");
System.out.println("int constructor");
}
Test(String n) {
this.n = n;
System.out.println("String constructor");
}
int getA() {
return a;
}
}
public static void main(String[] args) {
Num n = new Test();
n.getA();
}
// ์คํ ๊ฒฐ๊ณผ ===========
// String constructor
// int constructor
// default constructor
// 9
default ์์ฑ์ Test()๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ์ด๊ธฐํํ๋ฉด์ this(9)๊ฐ ์คํ๋๋ฉด์ int๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๋ฐ๋ ์์ฑ์ Test(int a)๊ฐ ํธ์ถ๋๋ค.
Test(9)๊ฐ ํธ์ถ๋๋ฉด์ a์ ๊ฐ์ ์ค์ ํ๊ณthis("hi")๋ฅผ ํตํดTest(Stirng n)์ ํธ์ถํ๋ค.Test(String)๊ฐ ํธ์ถ๋๋ฉด์ n์ ๊ฐ์ ์ค์ ํ๊ณ โString constructorโ์ ์ถ๋ ฅํ๊ณ ํธ์ถ์ ์ข ๋ฃ๋๋ค.Test(int)์์this("hi")์ ํธ์ถ์ด ์ข ๋ฃ๋์ผ๋ โint constructorโ์ ์ถ๋ ฅํ๊ณ ํธ์ถ์ ์ข ๋ฃํ๋ค.- ์ต์ข
์ ์ผ๋ก
Test()์์ โint constructorโ๊ฐ ์ถ๋ ฅ๋๋ฉด์ ๊ฐ์ฒด์ ์ด๊ธฐํ๊ฐ ์๋ฃ๋๋ค.
