부모클래스의 멤버와 자손클래스의 멤버가 동일한 경우
멤버변수 : 참조변수의 자료형을 따른다
멤버메서드 : 객체의 자료형을 따른다 객체의 최종 오버라이딩 된 메서드를 호출한다
class Parent2 {
int x = 10;
void method() {
System.out.println("Parent.method()");
}
}
class Child2 extends Parent2 {
int x = 20;
void method() {
System.out.println("Child2.method()");
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
public class BindingEx1 {
public static void main(String[] args) {
Child2 c = new Child2();
c.method();
System.out.println("c,x="+c.x);
Parent2 p = c;
p.method();
System.out.println("p.x="+p.x);
}
}
출력
Child2.method()
x=20
this.x=20
super.x=10
c,x=20
Child2.method()
x=20
this.x=20
super.x=10
p.x=10
부모 메서드를 출력하고 싶을 경우
super. 메서드를 추가해준다
class Child2 extends Parent2 {
int x = 20;
void method() {
super.method();
System.out.println("Child2.method()");
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
'JAVA > 개념' 카테고리의 다른 글
JAVA :: equals() 메서드와 == 연산자 차이 (0) | 2024.03.29 |
---|---|
JAVA :: 추상클래스, 추상메서드 (0) | 2024.03.29 |
JAVA :: @Override 오버라이드(오버라이딩), 상속의 다형성 (0) | 2024.03.28 |
JAVA :: super 예약어 (0) | 2024.03.28 |
JAVA :: 상속 (0) | 2024.03.28 |