[JAVA] this๋ž€?


Contents




this ๋ž€?

์ธ์Šคํ„ด์Šค์˜ ์ž๊ธฐ ์ž์‹ ์„ ์˜๋ฏธํ•œ๋‹ค.

  1. ์ž๊ธฐ ์ž์‹ ์˜ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๊ฐ€๋ฅดํ‚จ๋‹ค.
  2. ์ธ์Šคํ„ด์Šค ์ž์‹ ์˜ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
  3. ๋ณ€์ˆ˜๋ฅผ ๋ช…์‹œํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.

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)๊ฐ€ ํ˜ธ์ถœ๋œ๋‹ค.

  1. Test(9)๊ฐ€ ํ˜ธ์ถœ๋˜๋ฉด์„œ a์˜ ๊ฐ’์„ ์„ค์ •ํ•˜๊ณ  this("hi")๋ฅผ ํ†ตํ•ด Test(Stirng n)์„ ํ˜ธ์ถœํ•œ๋‹ค.
  2. Test(String)๊ฐ€ ํ˜ธ์ถœ๋˜๋ฉด์„œ n์˜ ๊ฐ’์„ ์„ค์ •ํ•˜๊ณ  โ€œString constructorโ€์„ ์ถœ๋ ฅํ•˜๊ณ  ํ˜ธ์ถœ์„ ์ข…๋ฃŒ๋œ๋‹ค.
  3. Test(int)์—์„œ this("hi")์˜ ํ˜ธ์ถœ์ด ์ข…๋ฃŒ๋์œผ๋‹ˆ โ€œint constructorโ€์„ ์ถœ๋ ฅํ•˜๊ณ  ํ˜ธ์ถœ์„ ์ข…๋ฃŒํ•œ๋‹ค.
  4. ์ตœ์ข…์ ์œผ๋กœ Test()์—์„œ โ€œint constructorโ€๊ฐ€ ์ถœ๋ ฅ๋˜๋ฉด์„œ ๊ฐ์ฒด์˜ ์ดˆ๊ธฐํ™”๊ฐ€ ์™„๋ฃŒ๋œ๋‹ค.





ยฉ 2022. by Yejin Ha

Powered by JihyunRyu