문제
다음 Java 코드의 빈칸에 들어갈 알맞은 단어는?
Javaclass Rectangle { int width, height; Rectangle(int width, int height) { this.width = width; this.height = height; } } class Square extends Rectangle { Square(int a) { ____(a, a); } int getSquareArea() { return width * height; } }
① this ② super ③ extends ④ implements
정답
2번
해설
정답: 2. 자식 클래스 생성자에서 부모 클래스 생성자를 호출할 때는 super(...)를 사용한다.
오답 풀이
- 1번: this(...)는 같은 클래스의 다른 생성자를 호출할 때 사용한다.
- 2번: 부모 생성자 Rectangle(int, int)를 호출해야 하므로 정답이다.
- 3번: extends는 클래스 상속 선언에 사용된다.
- 4번: implements는 인터페이스 구현에 사용된다.
보충 개념 Java에서 부모 클래스에 기본 생성자가 없으면 자식 생성자에서 명시적으로 super(...)를 호출해야 한다. super 호출은 생성자 첫 문장이어야 한다.