개발 수업/JAVA

[Java] 상속/부모 생성자 호출 super()

오늘 하루s 2023. 5. 17. 19:21
728x90
더보기

Day14-2. 230517

상속

부모 생성자 호출

- 자식 객체 생성할 때는 부모 객체 생성 후 자식 객체 생성

- 부모 생성자 호출 완료 후 자식 생성자 호출 완료

자식클래스(매개변수선언,...){
   super(매개값,...);
   ...
}

 

  • super(매개값,...)

- 매개값의 타입과 일치하는 부모 생성자 호출.

- 부모 생성자가 없다면 컴파일 오류 발생

- 부모 클래스에 기본(매개변수 없는) 생성자가 없다면 super(매개값,...)을 명시적으로 호출해야 함.

※주의. 반드시 자식 생성자의 첫 줄에 위치해야함.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package chap0607;
 
class GrandMother{
    GrandMother(int a){ System.out.println("GrandMother(int) 기본생성자 진입");}
    GrandMother(){/*super();*/ System.out.println("GrandMother() 기본생성자 진입");}
}
 
class Mother extends GrandMother{
    int a;
    Mother(int a){super(a); System.out.println("Mother(int) 기본생성자 호출");}
    Mother(){System.out.println("Mother() 기본생성자 호출");}
    void aa() {}
}
 
class Daughter extends Mother{
    Daughter(int b){
        super(b);
        System.out.println("Daughter(int)기본생성자 호출");
    }
    Daughter(){ 
        System.out.println("Daughter()기본생성자 호출");
        }
}
 
public class Super_p313 {
        public static void main(String[] args) {
            //딸 객체 생성
            Daughter d1 = new Daughter();
            System.out.println();
            
            Daughter d2 = new Daughter(100);
            System.out.println();
            
            Mother d3 = new Mother(2);
            System.out.println();
            
            GrandMother d4 = new GrandMother(2);
        }
}
cs
더보기

* 실행 결과

 

GrandMother() 기본생성자 진입
Mother() 기본생성자 호출
Daughter()기본생성자 호출

GrandMother(int) 기본생성자 진입
Mother(int) 기본생성자 호출
Daughter(int)기본생성자 호출

GrandMother(int) 기본생성자 진입
Mother(int) 기본생성자 호출

GrandMother(int) 기본생성자 진입

728x90