728x90
this를 어떨때에 쓸까
1학년 수업 - 객체지향프로그래밍2에서 this를 배웠는데 왜써야하는지 이해를 못했던 기억이 있다.
java를 공부하면서 완전히 이해했다.
this
this에는 가릴킬때 사용하는 this와 호출할때 사용하는 this메소드가 있다.
1) this
-> 생성한 객체 자신을 가리킨다!
class Circle{
private double radius; //멤버변수
public Circle(double radius) {
this.radius = radius;
}
}
멤버변수(인스턴스 변수)인 radius와 생성자의 인수로 받는 radius가 이름이 동일한것을 확인할수있다.
이때 인수와 멤버변수를 구별할수있도록 도와주는 것이 this이다.
this는 생성자로 생성한 객체 자신을 가리키는 "참조변수"이다. 객체의 주소가 저장되어있다.
즉 "."을 이용해 객체의 멤버변수인 radius에 접근할수있다!
2) this() // this메소드
-> 매개변수가 있는 기존의 생성자를 호출한다
class Circle{
private double radius;
private String color;
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public Circle(double radius) { //인수가 하나만 들어올때
this.radius = radius;
this.color = "파랑";
}
public Circle(String color) { //인수가 하나만 들어올때
this.radius = 10.0;
this.color = color;
}
}
위의 코드 주석과 같이 생성자 오버로딩할때에
this.radius = radius;
this.color = "파랑";
이처럼 두줄로 주어지지않은 변수를 기본값으로 설정해야하는 코드를 작성해야할때가 있다.
이때 기존에 매개변수가 존재하는 기존 생성자를 this메서드를 이용하여 호출할 수 있다.
class Circle{
private double radius;
private String color;
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public Circle(double radius) { //인수가 하나만 들어올때
this(radius, "파랑");
}
public Circle(String color) { //인수가 하나만 들어올때
this(10.0, color);
}
}
이런식으로 코드중복을 막을 수 있다.
반응형
'프로그래밍 > JAVA' 카테고리의 다른 글
java - 문자열[==,!=,compareTo, equals](6) (0) | 2021.08.23 |
---|---|
자바 - 정적멤버[static](5) (0) | 2021.08.21 |
자바 - [객체지향프로그래밍]-생성자와 생성자 오버로딩(3) (0) | 2021.07.28 |
자바 - JAVA [메서드,오버로딩](2) (0) | 2021.07.26 |
자바 기본 입출력[printf, println, scanner연산자](1) (0) | 2021.07.25 |