JAVA
[자바 공부] 상속 & 생성자 (정처기 문제)
100세까지 코딩
2023. 8. 10. 02:54
문제
class Parent {
int x = 100;
Parent() {
this(500); // this() : 자기자신 객체 생성자 호출
}
Parent(int x) {
this.x = x; // this : 객체 자기자신을 의미
}
int getX() {
return x;
}
}
class Child extends Parent {
int x = 4000;
Child() {
this(5000);
}
Child(int x) {
this.x = x;
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
System.out.println(obj.getX());
}
}
풀기 전 생각
- 정답은 100이라고 생각
- Child를 호출했으니 생성자를 통해 Child가 생성되고 x는 this(5000)으로 인해 5000으로 바뀜
- 그러나 getX()라는 함수는 Parent밖에 없으니 Parent의 처음 x값 100이 출력됨
풀이
상속 관계에서 하위객체를 생성하면 상위객체도 생성된다
즉, 자식객체가 생성될 때 생성자에 super()가 생략돼있는 것
정답 : 500
확인
추가 문제
public class Main {
public static void main(String[] args) throws Throwable {
Rectangle r;
r = new Rectangle();
}
}
class Shape {
private int x,y;
public Shape() {
this(0,0);
System.out.println("Shape 생성자");
}
public Shape(int xloc,int yloc) {
x = xloc; y=yloc;
System.out.println("Shape 유인 생성자");
}
}
class Rectangle extends Shape {
private int width, height;
public Rectangle() {
this(0,0,0,0);
System.out.println("Rectangle 생성자");
}
public Rectangle(int x,int y, int w, int h) {
width = w; height = h;
System.out.println("Rectangle 유인 생성자");
}
}
- 김병만, 『 자바만 잡아도』, 카오스북(2017), p267-268.
정답
더보기
Shape 유인 생성자
Shape 생성자
Rectangle 유인 생성자
Rectangle 생성자