Java

[Java] 상속관계에서의 Super와 Super()의 대해서 알아보기

joheamin 2025. 3. 26. 23:54

자바에서는 객체지향 프로그래밍으로 클래스 간의 상속이 가능하다.

 

 

상속해주는 클래스를 조상 클래스

상속 받는 클래스를 자식 클래스라고 한다.

 

 

🔍 간단한 상속 예제

Parent 클래스
class Parent{
	String name;

    //기본 생성자
    Parent(){};
    //초기화 생성자
    Parent(String name){
    	this.name = name;
    }
}


Child 클래스

class Child extends Parents{
	String gender;
    
    //기본 생성자
    Child(){};
    
    //초기화 생성자
    Child(String name,String gender){
	this.name = name;
    	this.gender = gender;
    }
}

 

👉 자손 클래스 인스턴스를 생성할 때  생성자로 받아온 인자로 this를 통하여 초기화

 

 


❓ Child 에는 name이라는 멤버 변수가 없는데 왜 this로 조상클래스 멤버변수에 접근이 가능할까? 

extends 를 통하여 상속을 받게 될 경우 조상의 멤버 변수와 멤버 메서드는 자손 클래스에서도 접근이 가능하다. 

 

 

🤔 만약 자손 클래스에 조상 클래스와 동일한 멤버 변수가 있다면?

class Child extends Parents{
	String name;   //조상 클래스와 동일한 변수명
	String gender;
    
    //기본 생성자
    Child(){};
    
    //초기화 생성자
    Child(String name,String gender){
	this.name = name;
    	this.gender = gender;
    }
}​

호출

Child child1 = new Child("홍길동","남자");
Person child2 = new Child("김영희","여자");

System.out.println(child1.name);
System.out.println(child2.name);

 

 

👉결과 분석

홍길동은 Child 객체를 참조하는 인스턴스
따라서 name을 호출하였을 때 Child 클래스에 변수가 호출된다.

김영희는 Person 객체를 참조하는 인스턴스  
따라서 name을 호출하였을 때 Person 클래스에 변수가 호출된다.

이때 Child에서의 생성자는 this.name 에 인자로 받은 name을 저장 
Child(String name,String gender){
	this.name = name;
    	this.gender = gender;
    }​


👉 조상과 자손의 변수명이 같을 경우에 this를 가리킬 경우 해당 클래스의 멤버를 우선으로 가리키게 된다.
      따라서 name은 this를 통해 조상 클래스에 name 이 아닌 자손클래스의 name에 저장된 것이다.

 

 

 

 

 

🔷 Super() 

조상의 생성자를 호출하는 메서드이며,

자손 클래스의 생성자에서 받은 인자를 전달하며 조상 클래스의 생성자를 호출한다.

 

Super()를 통한 조상 생성자 호출
//Child의 생성자
public Child(String name,String gender) {
		super(name);             //super를 통해 name을 전달
		this.gender = gender;
	}

출력하기

Child child1 = new Child("홍길동","남자");
Person child2 = new Child("김영희","여자");

System.out.println(child1.name);
System.out.println(child2.name);

👉 아까와 달리 조상클래스인 Person을 참조한 인스턴스에 name에 저장된것을 확인

 

 

🔷 Super 

자손 클래스에서 조상 클래스로부터 상속받은 멤버에 접근할때 사용한다.

자손 클래스가 자신의 멤버를 가리킬때는 this를 사용하고, 조상의 멤버를 가리킬 때 super를 사용하는것이다. 

 

 

🔍 조상과 자손의 name 값을 각각 지정하여 출력

조상 클래스와 자손의 이름을 각각 초기화
//조상 클래스
public class Person {
	String name = "엄마";
}

//자손 클래스
public class Child extends Person {
	String name = "자식";
 }

자손 클래스에서 각각의 name을 출력하는 메서드 생성

public void nameInfo() {
		System.out.printf("조상 이름:%s\n자손 이름:%s",super.name,this.name);
	}

👉 조상은 super , 자식은 this로 출력한다.


출력

public static void main(String[] args) {
	Child child1 = new Child();
	child1.nameInfo();
}