키보드워리어

[자바] 객체지향 - super키워드를 이용한 부모클래스 이용 본문

JAVA/입문

[자바] 객체지향 - super키워드를 이용한 부모클래스 이용

꽉 쥔 주먹속에 안경닦이 2023. 3. 9. 16:15
728x90

안녕하세요 【키보드 워리어】

 

⌨🗡🧑


블로그 방문자 여러분, 안경닦이입니다.

 

오늘은 자바 키워드 super에 대해 알아보겠습니다.

 


 

Super

 

super 키워드는 상속 관계에서 부모 클래스의 메서드나 멤버 변수를 자식 클래스에서 참조할 때 사용됩니다.

사용 예시를 보여드릴게요

 

public class Person {
    private String name;
    private String email;
    private String phoneNumber;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Name: %s , Email: %s, Phone Number: %s", name, email, phoneNumber);
    }
}

Person 클래스는 이름(name), 이메일(email), 전화번호(phoneNumber) 멤버 변수와, 생성자와 toString() 메서드를 갖고 있습니다.

 

그리고 Person을 상속받는 Employee 클래스가 있습니다.

public class Employee extends Person {
    private String title;
    private String employer;
    private char employeeGrade;
    private BigDecimal salary;

    public Employee(String name, String title) {
        super(name);
        this.title = title;
    }

    @Override
    public String toString() {
        return String.format("%s, Title: %s, Employer: %s, Grade: %c, Salary: %s", super.toString(), title, employer, employeeGrade, salary);
    }
}

Employee 클래스는 Person 클래스를 상속받아서, title, employer, employeeGrade, salary 멤버 변수와 생성자와 toString() 메서드를 추가로 갖고 있습니다.

 

이때 생성자에서는 super()를 이용해 부모 클래스인 Person 클래스의 생성자를 호출하여 이름을 초기화합니다.

 

Employee 클래스의 toString() 메서드에서는, super.toString()을 호출하여 Person 클래스의 toString() 메서드가 반환하는 문자열을 가져온 뒤, Employee 클래스의 title, employer, employeeGrade, salary 멤버 변수 값을 추가하여 반환합니다.

 

super키워드
super키워드

 super는 부모클래스 Person의 toString을 가져올 수 있게 해 줍니다.

 

 

초기 생성자와 super()메서드 호출

Person 클래스에 생성자가 있고, Employee 클래스에서도 생성자를 정의한다면,

Employee 클래스의 생성자에서는 명시적으로 super()를 호출하여 Person 클래스의 생성자를 실행해야 합니다. 만약 Employee 클래스에서 super()를 호출하지 않는다면, 컴파일 오류가 발생합니다!

생성자가 없어서 오류난 Employee
생성자가 없어서 오류난 Employee

아래는 Person 클래스와 Employee 클래스의 예시 코드입니다.

 

   public Person(String name) {
        this.name = name;
    }
   public Employee(String name, String title) {
        super(name); // 상위 클래스인 Person 클래스의 생성자를 호출하여 name을 초기화함
        this.title = title;
    }

Person 클래스와 Employee 클래스에서 각각 생성자가 정의되어 있습니다. Employee 클래스에서 super()를 사용하여 Person 클래스의 생성자를 명시적으로 호출하고 있습니다. 따라서, Employee 객체가 생성될 때, 먼저 Person 클래스의 생성자가 실행되고, 그다음에 Employee 클래스의 생성자가 실행됩니다.

 

상속 관계에서 하위 클래스는 상위 클래스의 속성과 메서드를 상속받을 수 있습니다. 하지만, 하위 클래스에서 새로운 생성자를 정의할 때에는 명시적으로 상위 클래스의 생성자를 호출해야 합니다. 이때, super 키워드를 사용하여 상위 클래스의 생성자를 호출할 수 있습니다.

 
728x90