Language/JAVA

(JAVA)상속-super, this

doheun 2023. 1. 19. 14:44
반응형

상속

부모클래스에서 정의한 속성과 메소드를 자식클래스에서 그대로 사용하는 것

this

현재 클래스의 멤버변수를 지정할 때 사용
현재 클래스의 생성자, 멤버필드 초기화

  • 현재의 클래스에서 외부로부터 변수의 이름이 같은 파라미터를 받을 경우에 현재 클래스의 멤버와 외부로부터 들어온 변수를 구분하기 위해서 this를 사용

super

하위클래스(자식)에서 상속받은 상위클래스(부모)의 멤버변수를 참조할 때 사용
부모의 생성자, 부모 멤버필드 초기화

코드

//부모클래스
public class Parent {
    public int num1;
    public int num2;

    public Parent() {
        this.num1 = 1;
        this.num2 = 2;
    }

    public Parent(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

}
//자식클래스
public class Child extends Parent {

    public int num3;
    public int num4;

    public Child() {
        //super(); 가 생략 : 항상 부모의 생성자 먼저 실행 후에 자식의 생성자 실행
        num3 = 3;
        num4 = 4;
    }

    public Child(int num3, int num4) {
        this.num3 = num3;
        this.num4 = num4;
    }

}

위와 코드와 같이 Parent클래스를 상속받은 자식클래스 Child클래스가 있다
각각 생성자로 Parent의 멤버변수 num1=1,num2=2와 Child의 멤버변수 num3=3, num4=4로 초기화를 시켜주었다
코드에서 this.num부분은 해당 클래스에서 클래스전역변수를 가리키는 것이고
(int num1, int num2)와 (int num3, int num4) 의 각각의 변수는 외부로부터 받는 매개변수인데 두개를 구분하기 위해서
클래스 전역변수에는 this를 붙여주는 것이다.

public class Main {

    public static void main(String[] args) {
        Child child=new Child();
        System.out.println("자식클래스(Child)의 변수 num3: "+child.num3);
        System.out.println("자식클래스(Child)의 변수 num4: "+child.num4);
        System.out.println("부모클래스(Parent)의 변수 num1: " +child.num1);
        System.out.println("부모클래스(Parent)의 변수 num2: " +child.num2);
    }

}
//자식클래스(Child)의 변수 num3: 3
//자식클래스(Child)의 변수 num4: 4
//부모클래스(Parent)의 변수 num1: 1
//부모클래스(Parent)의 변수 num2: 2

또한, 자식클래스 객체를 생성해서 실행시켰을 때 super를 이용하여 부모클래스의 클래스전역변수인 num1,num2를 참조해서
값을 자식클래스의 변수 값으로 변경해서 출력해보면 결과는 이렇게 나오게 된다.

public class Child extends Parent {

    public int num3;
    public int num4;

    public Child() {
        num3 = 3;
        num4 = 4;
        super.num1=num3;
        super.num2=num4;
    }

    public Child(int num3, int num4) {
        this.num3 = num3;
        this.num4 = num4;
    }

}
//자식클래스(Child)의 변수 num3: 3
//자식클래스(Child)의 변수 num4: 4
//부모클래스(Parent)의 변수 num1: 3
//부모클래스(Parent)의 변수 num2: 4

여기서 주의할 점은 자식클래스 객체를 만들어 실행 시키면 부모의 생성자가면서 실행 되기 때문에 num1=1,num2=2로 초기화가 먼저 되고 num3와 num4에 3,4가 들어가게 된다.

반응형

'Language > JAVA' 카테고리의 다른 글

(JAVA)인터페이스  (0) 2023.01.20
(JAVA)추상 클래스  (0) 2023.01.19
(JAVA)객체 지향 프로그래밍(OOP)  (0) 2023.01.18
(JAVA)로또  (0) 2023.01.17
(JAVA)배열  (0) 2023.01.16