[Java]this와 this(), super와 super()

Euiyeon Park·2024년 9월 1일

Java

목록 보기
5/16
post-thumbnail

🍀 this

this현재 객체 자신을 가리키는 참조 변수로 주로 생성자에서 객체의 인스턴스 변수(필드)와 메서드의 매개변수 이름이 같아 이를 구분하기 위해 사용된다.

💡 통상적으로 생성자에서 필드와 매개변수는 동일한 이름을 가진다.

  • this.value : 클래스의 인스턴스 변수
  • value : 메서드 또는 생성자의 매개변수
public class MyClass{
	private int value;
    
    public MyClass(int value){
    	this.value = value;
    }
    
    public void displayValue(){
		System.out.println(this.value);
    }
}

🍀 this()

this()동일 클래스 내의 다른 생성자를 호출할 때 사용한다.
생성자 오버로딩 시, 공통된 초기화 코드가 있을 때 이 코드를 반복하지 않고
다른 생성자를 호출해 코드 중복을 줄이는데 유용하다.

  • this()는 반드시 생성자의 첫 줄에서만 허용된다.
  • this()의 매개값은 호출되는 생성자의 매개변수에 맞게 제공해야 한다.
  • this() 다음에 추가적인 실행문이 있다면, 호출되는 생성자의 실행이 끝나면
    원래 생성자로 돌아와서 다음 실행문을 수행한다.

💡 this()를 호출하면 컴파일러는 전달된 인자 리스트를 바탕으로 해당 인자 리스트와 일치하는 생성자를 찾고, 생성자 시그니처를 기반으로 적합한 생성자를 선택한다.

public class Board {
	String title;
    String content;
    String writer;
    int viewCount;
    
    public Board(String title, String content){
    	this(title, content, "김아무개", 1);
        System.out.println("다른 생성자로 생성);
    }
    
    public Board(String title, String content, String writer){
    	this(title, content, writer, 1);
        System.out.println("다른 생성자로 생성);
    }
    
    public Board(String title, String content, String writer, int viewCount){
    this.title = title;
    this.content = content;
    this.writer = writer;
    this.viewCount = viewCount;
    }

🍀 super

super부모 클래스의 멤버(필드, 메서드)에 접근할 때 사용된다.
자식 클래스에서 부모 클래스의 멤버를 참조(접근)하거나, 부모 클래스의 메서드를 호출할 때 주로 사용된다.

  • super.value : 부모 클래스의 필드에 접근
  • super.display() : 부모 클래스의 메소드에 접근
class Parent{
	int value = 10;
    
    void display(){
    	System.out.println("Parent display method");
    }
}

class Child extends Parent{
	int value = 20;
    
    @Override
    void display(){
    	System.out.println("Child display mehthod");
    }
    
    void show(){
    	System.out.println("Child value: " + value);
        System.out.println("Parent value: " + super.value);
        
        display();
        super.display();
    }
}

🍀 super()

super()부모 클래스의 생성자를 호출할 때 사용된다.
자식 클래스의 생성자에서 명시적으로 부모 클래스의 특정 생성자를 호출하고 싶을 때
super()를 통해 호출한다.

public class Student {
	protected String name;
    protected int studentNo;
    
    public Student(String name, int studentNo){
    	this.name = name;
        this.studentNo = studentNo;
    }
    
    pulic void introduce(){
    	System.out.printf("name : %s, studentNo: %d", name, studentNo);
    }
}

public class Freshman extends Student{
	private String major;
    
    public Freshman(String name, int studentNo, String major){
    	super(name, studentNo);		// 부모 클래스 생성자 호출
        this.major = major;
    }
    
    @Override
    public void introduce(){
    	System.out.printf("name : %s, studentNo: %d, major: %s", name, studentNo, major);
    }
}

🍀 super()와 상속관계

부모 클래스를 물려받은 자식 클래스가 객체를 생성할 때, 이 객체는 독립적으로 생성되지 않고 부모 객체를 먼저 생성한 뒤에 자식 객체가 생성된다.

그리고 모든 객체는 클래스의 생성자를 호출해야만 생성된다.

그런데 컴파일러의 역할에 의해 코드상에서 이런 내부 동작을 눈치채기 어려울 수 있다.

public class Parent{
	// 부모 클래스 생성자
	public Parent(){
    	...
    }
}

public class Child extends Parent{
	// 자식 클래스 생성자
	public Child(){
    	...
    }
}

✅1. 자식 클래스의 객체는 부모 클래스의 객체를 먼저 생성해야 한다.
✅2. 모든 객체는 클래스의 생성자를 호출해야 한다.

두 가지 원칙에 의하면, 자식 클래스의 생성자에서 부모 클래스의 생성자를 호출해야 하는데, 코드에서 명시적으로 부모 클래스의 생성자를 호출하지 않기 때문이다.

하지만 사실은 컴파일러에 의해 부모 생성자는 자식 생성자의 맨 첫 줄에서 호출된다.

public class Child extends Parent{
	public Child(){
		super();
    	...
	}
}

클래스에서 생성자를 명시하지 않으면 컴파일러가 기본 생성자를 호출하듯이,
자식 클래스 생성자에서 명시적으로 부모 클래스 생성자를 호출하지 않으면
컴파일러가 super()를 삽입하여 통해 부모 클래스의 기본 생성자를 호출한다.

💡 super() 주의사항

super()부모 클래스의 기본 생성자를 호출하고,
기본 생성자는 매개변수가 없는 생성자이다.

따라서 부모 클래스에 기본 생성자가 없고, 매개변수가 있는 생성자만 있다면
자식 클래스의 생성자에서 super()를 호출할 때 반드시 해당 생성자의 매개변수에 맞는 값을 제공해야한다.

또한 super()반드시 자식 생성자의 첫 줄에 위치해야 한다.

정리

✅ 자식 클래스의 생성자에서 super()를 생략하면 컴파일러에 의해 자동으로 삽입되고,
super()는 부모 클래스의 기본 생성자를 호출하므로, 부모의 기본 생성자가 존재해야 한다.

✅ 부모 클래스의 생성자가 기본 생성자가 아니라면, 즉 매개변수가 있는 생성자라면
자식 클래스의 생성자에서 super()를 명시적으로 호출해야 하고,
매개변수에 맞는 값을 제공해야 한다.

super()는 반드시 자식 생성자의 첫 줄에 위치해야 한다.


마무리는 수수수수수퍼노바 ~
.  ∧_∧ ♪
(´・ω・`)  ♪
( つ つ
(( (⌒ __) ))
し' っ
사건은 다가와아 오에 ~

profile
"개발자는 해결사이자 발견자이다✨" - Michael C. Feathers

0개의 댓글