본문 바로가기
개발 노트/기초 지식

[java] this 와 super

by tokkiC 2022. 4. 25.

this

지역변수와 인스턴스 변수가 같은 경우 this 를 사용하여 클래스 명이 바뀌었을때 관리를 쉽게 할수있다

인스턴스 변수 : 클래스 내에서 선언한 변수

지역 변수 : 메소드 내에서 선언한 변수

super

상속관계에서 부모 클래스를 가져와서 매개변수에 값을 넣어 사용 시 super(매개변수) 를 사용한다
매개 변수가 없는 메소드를 가져올 시 매개변수를 넣으면 에러가 난다

"Unit.java"
public class Unit {
    int hitPoint;     //  인스턴스 변수 
    int speed;
    int range;
    int damage;

    public Unit(int a, int b, int c, int d) {
        this.hitPoint = a;    // Unit이라는 메소드 내의 지역 변수, 여기선 같은 Unit 클래스의 인스턴스 변수와 같으므로
        this.speed = b;       // this 를 써서 같은 클래스 내부의 변수를 가리킨다
        this.range = c;
        this.damage = d;
    }
}

"ProtossUnit.java"
public class ProtossUnit extends Unit {
    int shields;

    public ProtossUnit(int q, int w, int e, int r, int t) {
        super(q, w, e, r);       //  부모 클래스의 메소드를 가리키니 super 를 사용
        this.shields = t         //  이 지역변수는 같은 클래스 내의 인스턴스 변수를 가리키니 this 를 사용
    }
}

'개발 노트 > 기초 지식' 카테고리의 다른 글

[java] abstract  (0) 2022.04.25
[java] overload, override  (0) 2022.04.25
[java] 상속 extends  (0) 2022.04.25
[java] 접근제어자  (0) 2022.04.22
[java] static 의 이해  (0) 2022.04.21

댓글