4. super keyword
1. super
상속을 통해 상위 클래스를 참조하기 위해서는 super 키워드를 사용 따라서 super 키워드란 하위 클래스에서 상위 클래스로 접근할 때 사용하는 키워드라고 볼 수 있음
1-1. super
하위 클래스는 상위 클래스의 주소, 즉 참조 값을 가지고 있는데 이 값을 가지고 있는 키워드가 super
따라서 이러한 super 키워드를 통해 상위 클래스가 가진 필드에 접근하거나 메서드를 호출할 수 있음
Main.java
public class Main {
public static void main(String[] args) {
B b = new B();
b.methodB();
}
}A.java
class A {
int age;
void methodA() {
System.out.println("methodA() called");
}
}B.java
class B extends A{
void methodB() {
System.out.printf("A 클래스의 age 필드: %d \n", age);
super.methodA();
}
}this가 자기 자신의 참조값을 가지고 있는 것처럼 super도 마찬가지로 상위 클래스의 참조값을 가지고 있음
1-2. super()
이러한 super 키워드를 사용하여 상위 클래스의 생성자(constructor)를 호출할 수 있음
Main.java
public class Main {
public static void main(String[] args) {
B b = new B();
}
}A.java
class A {
public A() {
System.out.println("A() called");
}
}B.java
class B extends A{
public B() {
super(); // 상위 클래스의 기본 생성자 A() 호출
System.out.println("B() called");
}
}실행 결과
"A() called"
"B() called"1-1-1. 다른 예시
Animal 클래스
Animal.java
public class Animal {
private int age;
private String color;
public Animal() {}
public Animal(int age, String color) {
System.out.println("Animal(age, color) called");
this.age = age;
this.color = color;
}
public void sing() {
System.out.println("동물이 노래를 부른다.");
}
}Animal 클래스를 확장한 Mouse 클래스
Mouse.java
public class Mouse extends Animal {
private String address;
Mouse(int age, String color, String address) {
super(age, color);// 상위 클래스의 생성자 호출
System.out.println("Mouse(age, color, address) called");
this.address = address;
}
}Main 클래스
Main.java
public class Main {
public static void main(String[] args) {
Mouse jerry = new Mouse(15, "black", "플로리다");
System.out.println(jerry);
}
}실행 결과
"Animal(age, color) called"
"Mouse(age, color, address) called"
"jerry [age = 15, color = black, address = 플로리다]"1-1-2. 다양한 작성 방식
super(age, color)를 사용하여 age와 color를 초기화 하였는데, 문법적으로는 상위 클래스의 생성자를 호출하지 않고, 아래와 같이 하위 클래스에서 초기화를 작성할 수도 있음
Mouse.java
Mouse(int age, String color, String address) {
// super(age, color);
this.age = age;
this.color = color;
this.address = address;
}하지만 color와 address 필드는 Animal 클래스로부터 상속받았기 때문에, 해당 필드들은 하위 클래스에서 값을 초기화하는 것보다, 상위 클래스에서 내려받은 필드임을 명시하기 위해 super(age, color)를 사용하여 초기화하는 것이 권장됨
Mouse.java
Mouse(int age, String color, String address) {
super(age, color);
// this.age = age;
// this.color = color;
this.address = address;
}Last updated on