[Java] this와 super란?

지니·2025년 3월 2일

JAVA

목록 보기
3/9
post-thumbnail

1. this와 this()


1-1. this

객체 자신을 가리키는 레퍼런스 변수이다.

✅ 주로 지역변수와 인스턴스 변수를 구별할 때 사용된다.

  • 생성자1 : 매개변수명과 필드명이 다르기 때문에 잘 구분이 되어 초기화가 일어난다.
  • 생성자2 : 매개변수명과 필드명이 동일한데, 구분이 되지 않아 초기화가 원하는 대로 일어나지 않는다.
  • 생성자3 : 매개변수명과 필드명이 동일하다. 그런데 인스턴스 변수명엔 this를 붙여서 변수를 구분해주고 있다. 결과적으로 초기화가 원하는 대로 일어나고 있다.
// Clothes.java
public class Clothes {
    private String name;
    private int price;
    private String brand;
	
    // 생성자 1 : 매개변수명과 필드명이 다름
    public Clothes(String a) {
            name = a;
    }

	// 생성자 2 : 매개변수명과 필드명이 동일 (this를 사용하지 않음)
    public Clothes(String name, int price) {
        name = name;
        price = price;
    }
    
	// 생성자 3 : 매개변수명과 필드명이 동일 (this를 사용)
    public Clothes(String name, int price, String brand) {
        this.name = name;
        this.price = price;
        this.brand = brand;
    }

    public String getInformation(){
        return this.name + "," + this.price + "," + this.brand);
    }
}

// Test.java
public class Test {
    public static void main(String[] args) {
    	// name이 맨투맨으로 초기화
        Clothes top1 = new Clothes("맨투맨");
        // 맨투맨, 0, null
        System.out.println(top1.getInformation());

		// name, price가 원하는 값으로 초기화 되지 않고 기본값으로 초기화
        Clothes top2 = new Clothes("후드티",45000);
        // null, 0, null
        System.out.println(top2.getInformation());

		// name, price, brand가 모두 원하는 값으로 초기화
        Clothes top3 = new Clothes("블라우스",1000000,"미우미우");
        // 블라우스,1000000,미우미우
        System.out.println(top3.getInformation());

    }
}

1-2. this()

생성자에서 다른 생성자를 호출할 때 사용한다.

✅ 생성자 코드의 중복을 줄이고 초기화 과정을 단순화하는데 유용하다.

public class Clothes {
    private String type;
    private String name;
    private int price;
    private String brand;

    public Clothes(){}

	// 생성자 1
    public Clothes(String type, String name){
        this.type = type;
        this.name = name;
    }

	// 생성자 2
    public Clothes(String type, String name, int price, String brand) {
        this(type,name); // 생성자1을 호출
        this.price = price;
        this.brand = brand;
    }
}

2. super와 super() - 상속


2-1. super

부모 객체의 주소를 보관하는 참조 변수이다.
자식 클래스 내의 모든 생성자와 메소드 내에서 묵시적으로 사용할 수 있는 레퍼런스 변수다.

  • 필드명의 중복 또는 메소드의 오버라이딩으로 가려진 부모의 멤버를 호출하기 위해 사용한다.
  • Parent가 부모 클래스, Child가 자식 클래스이다.
// Parent.java
public class Parent {
    String name = "홍길동";
}

// Child.java
public class Child extends Parent {
    String name = "이순신";

    public void getName(){
        System.out.println(this.name);
        // super는 부모 객체의 주소를 보관한다.
        // 결과적으로 부모에 있는 "홍길동"을 출력한다.
        System.out.println(super.name);
    }
}

// Test.java
public class Test{
    public static void main(String[] args) {
        Child child = new Child();

        child.getName();
        // 이순신, 홍길동이 출력되는 것을 확인 할 수 있다. 
    }
}

2-2. super()

부모 클래스의 생성자를 호출하는 구문으로 명시적 or 묵시적으로 사용 가능하다.

  • 모든 클래스는 Object라는 부모 클래스를 가지고 있어도, 지금까지 생성자를 만들 때 super()라는 것을 다로 작성하지 않았다.
  • 이는 컴파일러가 super()를 맨 첫 줄에 자동으로 추가해줬기 때문이다.

✅ 참고로 super()와 this()는 동시에 사용할 수 없다.

0개의 댓글