๋ฐ์ํ
โถ this ์์ฝ์ด
this๋ ์์ฑ๋ ์ธ์คํด์ค ์ค์ค๋ก๋ฅผ ๊ฐ๋ฆฌํค๋ ์์ฝ์ด.
package thisex;
class BirthDay {
int day;
int month;
int year;
public void setYear(int year) { // ํ์ด๋ ์ฐ๋๋ฅผ ์ง์ ํ๋ ๋ฉ์๋
this.year = year;
}
public void printThis() { // this ์ถ๋ ฅ ๋ฉ์๋
System.out.println(this); // this ์ถ๋ ฅํด๋ณด๊ธฐ
}
}
public class ThisExmaple {
public static void main(String[] args) {
BirthDay bDay = new BirthDay();
bDay.setYear(2000); // ํ์ด๋ ์ฐ๋๋ฅผ 2000์ผ๋ก ์ง์
System.out.println(bDay); // ์ฐธ์กฐ ๋ณ์ ์ถ๋ ฅ
bDay.printThis(); // this ์ถ๋ ฅ ๋ฉ์๋ ํธ์ถ
}
}
<๊ฒฐ๊ณผ๊ฐ>
โถ ์์ฑ์์์ ๋ค๋ฅธ ์์ฑ์๋ฅผ ํธ์ถํ๋ this
package thisex;
class Person {
String name;
int age;
Person() {
this("์ด๋ฆ์์", 1); // this๋ฅผ ์ฌ์ฉํด Person(String, int) ์์ฑ์ ํธ์ถ
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public class CallAnotherConst {
public static void main(String[] args) {
Person noName = new Person();
System.out.println(noName.name);
System.out.println(noName.age);
}
}
-์์ฑ์๋ฅผ ๋จผ์ ์์ฑํ ํ์ ๊ฐ์ ํธ์ถํด์ผํ๋ค.
โถ ์์ ์ ์ฃผ์๋ฅผ ๋ฐํํ๋ this
package thisex;
class Person {
String name;
int age;
Person() {
this("์ด๋ฆ์์", 1); // Person(String, int) ์์ฑ์ ํธ์ถ
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
Person returnItSelf() { // ๋ฐํํ์ ํด๋์คํ
return this;
}
}
public class CallAnotherConst {
public static void main(String[] args) {
Person noName = new Person();
System.out.println(noName.name);
System.out.println(noName.age);
Person p = noName.returnItSelf();
System.out.println(p);
System.out.println(noName);
}
}
๋ฐ์ํ
'Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java] Static ๋ณ์ (0) | 2021.02.18 |
---|---|
[Java] ๊ฐ์ฒด ๊ฐ ํ๋ ฅ (0) | 2021.02.18 |
[Java] ์ฐ์ต๋ฌธ์ + ์ค์ต (0) | 2021.02.18 |
[Java] ์ ๋ณด ์๋ (0) | 2021.02.18 |
[Java] ์ฐธ์กฐ ์๋ฃํ (0) | 2021.02.18 |
๋๊ธ