반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
05-19 00:03
관리 메뉴

ImJay

[자바] 자식 클래스 객체 초기화 본문

자바/기본 개념

[자바] 자식 클래스 객체 초기화

ImJay 2022. 7. 4. 17:40
반응형

부모 클래스로부터 상속 받은 자식 객체는 생성자를 어떻게 만들까?

public class Child extends Parent {
    private int x;
    
    public Child() {
        this(0, 0, 0, 0);
    }
    
    public Child(int a, int b, int c, int x) {
        this.setA(a);
        this.setB(b);
        this.setC(c);
        this.x = x;
    }

}

위와 같은 방법으로 setter를 호출하여 값을 초기화 시켜줄 수 있다.

그러나, 꽤나 비효율적으로 보인다.

 

우리는 매개변수가 없는 생성자와 부모 클래스를 지칭하는 super로부터 힌트를 얻어 아래와 같은 방법을 사용할 수 있다.

public class Child extends Parent {
    private int x;
    
    public Child() {
        this(0, 0, 0, 0);
    }
    
    public Child(int a, int b, int c, int x) {
        super(a, b, c);
        this.x = x;
    }

}

부모 클래스를 지칭하는 super 메소드를 통해 훨씬 간단하게 자식 클래스를 만드는 방법에 대해 알아보았다.

반응형
Comments