java oop 26 참조변수 super

bitcogo·2022년 7월 26일
0

참조변수 super

  • 조상의 멤버를 자신의 멤버와 구별할 때 사용
  • 자신의 멤버 this 조상의 멤버 super
public class Oop26_super {
    public static void main(String[] args) {

        Child5 c1 = new Child5();
        c1.method();
        System.out.println("////////////////////////////////");
        Child6 c2 = new Child6();
        c2.method();
    }
}

class Parent5{ int x = 10;/* super.x */ }

class Child5 extends Parent5 {

    int x = 20;//this.x

    void method() {
        System.out.println("x="+x);//무작정 x라고 하면 가까운 것을 호출하기 때문에 x=20
        System.out.println("this.x="+this.x);
        System.out.println("super.x="+super.x);
    }
}

class Parent6{ int x = 10; /*super.x와 this.x 둘다 가능*/}

class Child6 extends Parent6 {

    void method() {
        System.out.println("x="+x);
        System.out.println("this.x="+this.x);
        System.out.println("super.x="+super.x);
        //멤버변수가 중복되지 않을때는 this.x와 super.x가 가르키는 것이 같다
    }
}
profile
공부하고 기록하는 블로그

0개의 댓글