본문 바로가기
Spring-Java/Java

super, super()

by 현대타운301 2024. 4. 24.

 

세 줄 요약

- super : 부모 클래스로부터 상속받은 필드나 메소드를 사용하기 위한 참조변수

- super() : 부모 클래스로부터 상속받은 필드의 값을 초기화 해주는 메소드(= 생성자 역할)

- super() 메소드는 자동으로 추가되나, 부모 클래스에 매개변수를 갖는 생성자가 있는 경우 기본 생성자를 추가해줘야 함

 


 

super?

 

super

super 키워드는 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는데 사용하는 참조 변수입니다.

 

 

this와 super

인스턴스 필드와 지역 변수의 이름이 같을 때 this 키워드로 인스턴스 필드임을 구분했습니다.

class Parent {
    int a;
    
    public Parent(int a) {
        this.a = a;	// this가 붙은 a는 인스턴스 필드 a
    }
}

 

이와 마찬가지로 super를 통해 부모 클래스의 필드(혹은 메소드)임을 명시할 수 있습니다.

class Parent {
    int a = 20;
}

class Child extends Parent {
    int a = 10;
    
    public void display() {
    	System.out.println("인스턴스 필드 a = " + a);
        System.out.println("부모 클래스 필드 a = " + super.a);
    }
}

public class Main {
    public static void main(String[] args) {
    	Child child = new Child();
        child.display();
    }
}

 

실행결과

인스턴스 필드 a = 10
부모 클래스 필드 a = 20

 


 

super( )

 

super( )

부모 클래스의 생성자를 호출해 필드의 값들을 초기화하는 역할을 합니다.

 

 

this( )와 super( )

같은 클래스의 다른 생성자를 호출할 때 this() 메소드를 사용했습니다.

생성자 내부에서만 사용할 수 있으며, 첫 번째 줄에서만 다른 생성자를 호출할 수 있습니다.

또한 메소드에 인자를 전달하면 해당 메소드 시그니처에 맞는(= 타입과 개수가 맞는) 생성자를 호출합니다.

class Friends {
    String name;
    String sex;
    int age;
    String hobby;
    
    public Friends(String name, String sex, int age, String hobby) {
    	this.name = name;
        this.sex = sex;
        this.age = age;
        this.hobby = hobby;
    }

    // 인자가 아무것도 없는 생성자를 통해 인스턴스를 생성하면
    // 매개변수가 String, String, int, String인 생성자를 자동으로 호출
    public Friends() {
    	this("김자바", "남", 19, "프로그래밍");
    }
    
    public void getInformation() {
    	return "이름 : " + this.name + ", 성별 : " + this.sex + ", 나이 : " + this.age + ", 취미 : " + this.hobby;
    }
}

public class Main {
    public static void main(String[] args) {
        Friends friends = new Friends();	// 인자로 아무것도 넘기지 않는 생성자로 Friends 인스턴스 생성
        System.out.println(friends.getInformation());
    }
}

 

실행결과

이름 : 김자바, 성별 : 남, 나이 : 19, 취미 : 프로그래밍

 

super( ) 메소드는 부모 클래스의 필드 초기화를 담당합니다.

자바 컴파일러에 의해 자동으로 기본 생성자를 호출하는 super() 메소드가 추가됩니다.

단, 부모 클래스에 매개변수를 갖는 생성자가 존재하면 기본 생성자를 추가해야 super() 메소드를 사용할 수 있습니다.

this()와 마찬가지로 메소드에 인자를 전달하면 해당 메소드 시그니처에 맞는 생성자를 호출합니다.

class Parent {
    int a;

    public Parent() {
        a = 10;
    }

    // 매개변수를 갖는 생성자가 존재하기 때문에
    // 기본 생성자를 정의해야 super() 메소드를 사용할 수 있다.
    public Parent(int a) {
        this.a = a;
    }
}

class Child extends Parent {
    int b;

    public Child() {
        super(30);	// super(30)에 의해 a = 30으로 초기화
        b = 20;
    }

    public void display() {
        System.out.println(a);
        System.out.println(b);
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}

 

실행결과

10
30

 


 

super( ) 메소드의 활용

 

커스텀 예외 만들기

조회한 도메인 객체를 찾지 못하는 경우 NoSuchElementException 대신 'EntityNotFoundException'을 발생시킵니다.

해당 예외는 RuntimeException을 상속받아 Unchecked Exception으로 처리합니다.

 

EntityNotFoundException.java

public class EntityNotFoundException extends RuntimeException {
    public EntityNotFoundException(String message) {
        super(message);
    }
}

 

super(message)에 의해 부모 클래스인 RuntimeException의 String 타입 매개변수 하나만 갖는 생성자를 통해 초기화를 진행합니다.

RuntimeException 클래스는 다시 부모 클래스인 Exception 클래스의 생성자를 호출하고,

Exception 클래스는 다시 부모 클래스인 Throwable의 생성자를 호출합니다.

 

결과적으로 EntityNotFoundException 생성자의 super(message) 메소드 실행결과는 다음과 같습니다.

 

1) Throwable 클래스의 fillInStackTrace() 메소드 호출

2) detailMessage 필드를 인자로 넘겨준 message로 초기화

 

예외 결과를 확인하기 위해 아래와 같이 Repository를 구성하고 요청으로 예외가 발생하는 상황을 보내봅니다.

 

ProductRepository

public class ProductRepository {

    private List<Product> products = new CopyOnWriteArrayList<>();
    
    public Product findById(Long id) {
    	return products.stream()
            .filter(product -> product.sameId(id))
            .findFirst()
            .orElseThrow(() -> new EntityNotFoundException("Product를 찾지 못했습니다."));
    }
}

 

실행결과

postman 요청 결과

 

 

 

* refs

https://www.tcpschool.com/java/java_inheritance_super

 

 

 

'Spring-Java > Java' 카테고리의 다른 글

Optional 클래스  (2) 2024.04.05
스트림(Stream)_최종 처리 기능  (0) 2024.04.05
스트림(Stream)_중간 처리 기능  (1) 2024.04.04
익명 객체와 람다식(lambda)  (0) 2024.04.03
Day10_class 예제  (0) 2023.08.28