๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] this ์˜ˆ์•ฝ์–ด

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 18.
๋ฐ˜์‘ํ˜•

โ–ถ 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

๋Œ“๊ธ€