자바/기본 개념
[자바] 자식 클래스 객체 초기화
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 메소드를 통해 훨씬 간단하게 자식 클래스를 만드는 방법에 대해 알아보았다.
반응형