๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ/Java

[Java] this(): ์ฝ”๋“œ๋กœ this() ๋ฉ”์†Œ๋“œ ์ดํ•ดํ•˜๊ธฐ

by HanaV 2023. 3. 19.
728x90

์ฑ…์˜ ์ œ๋ชฉ๊ณผ ์ž‘๊ฐ€์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด this() ํ•จ์ˆ˜์— ๋Œ€ํ•ด ์ดํ•ดํ•ด๋ณด์ž

 

์ „์ฒด์ฝ”๋“œ

package Chapter04;

public class Book {
	
	String title;
	String author;
	
    //show method
	void show() {
		System.out.println(title + " - " + author);
	}
	
    //์ƒ์„ฑ์ž1
	public Book() {
		this("", "");
	}
	
    //์ƒ์„ฑ์ž2
	public Book(String title) {
		this(title, "์ž‘์ž๋ฏธ์ƒ");
	}
	
    //์ƒ์„ฑ์ž3
	public Book(String title, String author) {
		this.title = title;
		this.author = author;
	}
	
	
	public static void main(String[] args) {
		Book LittlePrince = new Book("์–ด๋ฆฐ์™•์ž", "์ƒํƒ์ฅ๋ฒ ๋ฆฌ"); //๊ฐ์ฒด1
		Book LoveStory = new Book("์ถ˜ํ–ฅ์ „"); //๊ฐ์ฒด2
		Book Empty = new Book(); //๊ฐ์ฒด3
		LoveStory.show(); //์‹คํ–‰1
		LittlePrince.show(); //์‹คํ–‰2
		Empty.show(); //์‹คํ–‰3
	}
}

 

์‹คํ–‰ ์ˆœ์„œ

1. ์‹คํ–‰1 : LoveStory ๊ฐ์ฒด๋ฅผ show method์— ์‹คํ–‰์‹œ์ผœ๋ผ  >>  ๊ฐ์ฒด2 

2. ๊ฐ์ฒด2๋Š” ๋ณ€์ˆ˜๊ฐ€ 1๊ฐœ  (title - ์ถ˜ํ–ฅ์ „)  >>  ๋ณ€์ˆ˜ 1๊ฐœ๋ฅผ ๋ฐ›๋Š” ์ƒ์„ฑ์ž2๋กœ (title - ์ถ˜ํ–ฅ์ „ author - ์ž‘์ž๋ฏธ์ƒ)

3. ์ƒ์„ฑ์ž2 ์•ˆ์— this.()๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ 2๊ฐœ  >>  ๋ณ€์ˆ˜ 2๊ฐœ๋ฅผ ๋ฐ›๋Š” ์ƒ์„ฑ์ž3์œผ๋กœ

4. ์ƒ์„ฑ์ž3์—์„œ title๊ณผ author์— ์ •๋ณด ์ž…๋ ฅ 

5. show method์— ๋ณ€์ˆ˜ ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•ด์„œ ํ•จ์ˆ˜ ์‹คํ–‰

>>์ถ˜ํ–ฅ์ „ - ์ž‘์ž๋ฏธ์ƒ

 

6. ์‹คํ–‰2: LittlePrince ๊ฐ์ฒด๋ฅผ show method์— ์‹คํ–‰์‹œ์ผœ๋ผ  >>  ๊ฐ์ฒด1

7. ๊ฐ์ฒด1์€ ๋ณ€์ˆ˜๊ฐ€ 2๊ฐœ  (title - ์–ด๋ฆฐ์™•์ž, author - ์ƒํƒ์ฅ๋ฒ ๋ฆฌ)  >>  ๋ณ€์ˆ˜ 2๊ฐœ๋ฅผ ๋ฐ›๋Š” ์ƒ์„ฑ์ž3์œผ๋กœ

8. ์ƒ์„ฑ์ž3์—์„œ title๊ณผ author์— ์ •๋ณด ์ž…๋ ฅ

9. show method์— ๋ณ€์ˆ˜ ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•ด์„œ ํ•จ์ˆ˜ ์‹คํ–‰

>>์–ด๋ฆฐ์™•์ž - ์ƒํƒ์ฅ๋ฒ ๋ฆฌ

 

10. ์‹คํ–‰3: Empty ๊ฐ์ฒด๋ฅผ show method์— ์‹คํ–‰์‹œ์ผœ๋ผ  >>  ๊ฐ์ฒด3

11. ๊ฐ์ฒด3์€ ๋ณ€์ˆ˜๊ฐ€ 0๊ฐœ  >>  ๋ณ€์ˆ˜๋ฅผ 0๊ฐœ ๋ฐ›๋Š” ์ƒ์„ฑ์ž1๋กœ (title - , author - )

12. ์ƒ์„ฑ์ž1 ์•ˆ์— this()๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ 2๊ฐœ  >>  ๋ณ€์ˆ˜๋ฅผ 2๊ฐœ ๋ฐ›๋Š” ์ƒ์„ฑ์ž3์œผ๋กœ

13. ์ƒ์„ฑ์ž3์—์„œ title๊ณผ author์— ์ •๋ณด ์ž…๋ ฅ

14. show method์— ๋ณ€์ˆ˜ ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•ด์„œ ํ•จ์ˆ˜ ์‹คํ–‰

>> - 

 

console

์ถ˜ํ–ฅ์ „ - ์ž‘์ž๋ฏธ์ƒ
์–ด๋ฆฐ์™•์ž - ์ƒํƒ์ฅ๋ฒ ๋ฆฌ
 -

 

728x90

"); wcs_do();