5. super()의 암묵적 호출
하위 클래스의 생성자에서 super()를 작성하지 않을 경우, 내부적으로 상위 클래스의 기본 생성자가 호출됨
Animal 클래스
Animal.java
public class Animal {
private int age;
private String color;
public Animal() {
System.out.println("Animal() called");
}
public Animal(int age, String color) {
System.out.println("Animal(age, color) called");
this.age = age;
this.color = color;
}
}Mouse 클래스
Mouse.java
public class Mouse extends Animal {
private String address;
Mouse(int age, String color, String address) {
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", "플로리다");
}
}실행 결과
"Animal() called"
"Mouse(age, color, address) called"
"jerry [age = 15, color = black, address = 플로리다]"상위 클래스의 생성자가 먼저 호출되는 이유는, 하위 클래스의 인스턴스를 생성하기 위해서는 상위 클래스의 인스턴스를 먼저 생성해서 특성을 상속시켜, 하위 클래스의 인스턴스가 생성되는 시점부터는 해당 특성을 사용할 수 있어야하기 때문
Last updated on