자바 상속 및 this에 관하여 질문드립니다.
-
게시물 수정 , 삭제는 로그인 필요
public class Main {
public static void main(String[] args) {
A b = new B();
b.draw();
}
}
class A {
int a = 10;
public void draw() {
System.out.println(this);
System.out.println(this.a);
this.draw();
}
}
class B extends A {
int a = 20;
public void draw() {
System.out.println("=========== 자식 클래스 ===========");
System.out.println(this);
System.out.println(this.a);
System.out.println("=========== 부모 클래스 ===========");
super.draw();
}
}
결과
=========== 자식 클래스 ===========B@1b6d358620=========== 부모 클래스 ===========B@1b6d358610
안녕하새요 자바 상속 및 this에 관하여 질문드립니다.
B가 A를 상속 받고 있습니다.
this가 현재 생성 객체의 주소로 알고 있는데요!
그래서 this의 주소를 출력해보면 부모, 자식 예상한대로 B의 주소가 노출되고 있습니다.
여기서 this.a는 왜 서로 다른 값이 노출되고 부모에서 작성한 this.draw()를 오버라이딩을
진행한 자식의 draw()로 호출되는지 잘 이해가 가지 않습니다.
고수님들의 설명 부탁드립니다 ㅠㅠㅠ
감사합니다.
public class Main {
public static void main(String[] args) {
A b = new B();
b.draw();
}
}
class A {
int a = 10;
public void draw() {
System.out.println(this);
System.out.println(this.a);
this.draw();
}
}
class B extends A {
int a = 20;
public void draw() {
System.out.println("=========== 자식 클래스 ===========");
System.out.println(this);
System.out.println(this.a);
System.out.println("=========== 부모 클래스 ===========");
super.draw();
}
}
결과
=========== 자식 클래스 ===========B@1b6d358620=========== 부모 클래스 ===========B@1b6d358610
안녕하새요 자바 상속 및 this에 관하여 질문드립니다.
B가 A를 상속 받고 있습니다.
this가 현재 생성 객체의 주소로 알고 있는데요!
그래서 this의 주소를 출력해보면 부모, 자식 예상한대로 B의 주소가 노출되고 있습니다.
여기서 this.a는 왜 서로 다른 값이 노출되고 부모에서 작성한 this.draw()를 오버라이딩을
진행한 자식의 draw()로 호출되는지 잘 이해가 가지 않습니다.
고수님들의 설명 부탁드립니다 ㅠㅠㅠ
감사합니다.
#자바 상속 #자바 상속 예제 #자바 상속 생성자 #자바 상속 오버라이딩 #자바 상속관계 #자바 상속 super #자바 상속 오버라이딩 예제 #자바 상속 다형성 #자바 상속 생성자 호출 순서 #자바 상속 문제