๐ this,this()
1. this : ๊ฐ์ฒด ์์ ์ ๊ฐ๋ฆฌํค๋ ์ฐธ์กฐ๋ณ์
this๋ ์ธ์คํด์ค ์์ ์ ๊ฐ๋ฆฌํค๋ ์ฐธ์กฐ๋ณ์์ด๋ค.
๋ฉ์๋ ๋ด์์๋ง ์ฌ์ฉ๋๊ณ static ๋ฉ์๋์์๋ ์ฌ์ฉ์ด ๋ถ๊ฐ๋ฅํ๋ค.
๋ฉค๋ฒ ๋ณ์๋ฅผ ๊ฐ๋ฆฌํฌ ๋๋ ๋งค๊ฐ๋ณ์์ ๊ตฌ๋ถํ๊ธฐ ์ํด this.๋ฉค๋ฒ๋ณ์ ํ์์ผ๋ก ์ฌ์ฉํ๋ค.
Car(String c, String g, int d){
color = c;
gearType = g;
door = d;
}
์ด ์ฝ๋๋ฅผ ๋ดค์ ๋ 'color = c;'๋ ์์ฑ์์ ๋งค๊ฐ๋ณ์๋ก ์ ์ธ๋ ์ง์ญ๋ณ์ c์ ๊ฐ์ ์ธ์คํด์ค๋ณ์ color์ ์ ์ฅํ๋ค.
์ด ๋ ๋ณ์ color์ c๋ ์ด๋ฆ๋ง์ผ๋ก๋ ์๋ก ๊ตฌ๋ณ๋๋ฏ๋ก ์๋ฌด ๋ฌธ์ ๊ฐ ์๋ค.
Car(String color, String geerType, int door){
this.color = color;
this.gearType = gearType;
this.door = door;
}
ํ์ง๋ง, ์ด ์ฝ๋์์์ฒ๋ผ ์์ฑ์์ ๋งค๊ฐ๋ณ์๋ก ์ ์ธ๋ ๋ณ์์ ์ด๋ฆ์ด color๋ก ์ธ์คํด์ค๋ณ์ color์ ๊ฐ์ ๊ฒฝ์ฐ์๋ ์ด๋ฆ๋ง์ผ๋ก๋ ๊ตฌ๋ณ์ด ์๋๋ค!
์ด๋ฐ ์ํฉ์์, ์ธ์คํด์ค๋ณ์ ์์ 'this'๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.
2. this() : ์์ฑ์์์ ๋ค๋ฅธ ์์ฑ์ ํธ์ถํ๊ธฐ
์์ฑ์ ๊ฐ์๋ ์๋ก ํธ์ถ์ด ๊ฐ๋ฅํ๋ค. ๋์ ๋๊ฐ์ง์ ์กฐ๊ฑด์ ๋ง์กฑ์์ผ์ผ ํ๋ค.
- ์์ฑ์์ ์ด๋ฆ์ผ๋ก ํด๋์ค์ด๋ฆ ๋์ this๋ฅผ ์ฌ์ฉํ๋ค.
- ํ ์์ฑ์์์ ๋ค๋ฅธ ์์ฑ์๋ฅผ ํธ์ถํ ๋๋ ๋ฐ๋์ ์ฒซ ์ค์์๋ง ํธ์ถ์ด ๊ฐ๋ฅํ๋ค.
Car c = new Car();
c.color = "white";
c.gearType = "auto";
c.door = 4;
Car ์ธ์คํด์ค๋ฅผ ์์ฑํ ๋, ์์ฑ์ Car()๋ฅผ ์ฌ์ฉํ๋ค๋ฉด, ์ธ์คํด์ค๋ฅผ ์์ฑํ ๋ค์์ ์ธ์คํด์ค ๋ณ์๋ค์ ๋ฐ๋ก ์ด๊ธฐํํด์ผํ๋ค.
ํ์ง๋ง, ๋งค๊ฐ๋ณ์๊ฐ ์๋ ์์ฑ์ Car(String color, String gearType, int door)๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ ๋์์ ์ํ๋ ๊ฐ์ผ๋ก ์ด๊ธฐํ๋ฅผ ํ ์ ์๊ฒ ๋๋ค.
์ด๋ฌํ ๋ฐฉ๋ฒ์ผ๋ก ํ์ ๋์ ์ฝ๋(์๋ ์ฝ๋)๋ฅผ ๋ณด๋ฉด, ํจ์ฌ ๋ ์ง๊ด์ ์ด๊ณ ๊ฐ๊ฒฐํ๋ค.
Car c = new Car("white","auto",4);
์ด์ฒ๋ผ ์ธ์คํด์ค ์์ฑ ํ์ ๋ณ๋๋ก ์ด๊ธฐํ๋ฅผ ํ์ง ์์๋ ๋๋๋ก ํ์
3. ๊ฐ๋จ ์ ๋ฆฌ
๊ฐ๋จ ์ ๋ฆฌ(this, this())
this : ์ธ์คํด์ค ์์ ์ ๊ฐ๋ฆฌํค๋ ์ฐธ์กฐ๋ณ์, ์ธ์คํด์ค์ ์ฃผ์๊ฐ ์ ์ฅ๋์ด ์๋ค.
๋ชจ๋ ์ธ์คํด์ค ๋ฉ์๋์ ์ง์ญ๋ณ์๋ก ์จ๊ฒจ์ง ์ฑ๋ก ์กด์ฌํ๋ค.
this(), this(๋งค๊ฐ๋ณ์) : ์์ฑ์, ๊ฐ์ ํด๋์ค์ ๋ค๋ฅธ ์์ฑ์๋ฅผ ํธ์ถ ํ ๋ ์ฌ์ฉํ๋ค.
'โค๏ธ JAVA > Basic' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] ์์ธ๋?(Exception) (0) | 2024.10.24 |
---|---|
[JAVA] super์ super() (0) | 2024.10.21 |
[JAVA] ์์(Inheritance) (0) | 2024.10.20 |
[JAVA] ์ ์ด์(modifier) (0) | 2024.10.18 |
[JAVA] ์์ฑ์(consructor) (0) | 2024.10.17 |