java 기초-this

이호영·2021년 12월 28일
0

java

목록 보기
3/6
post-thumbnail

this 연산자란? 메소드안에서 선언된 변수를 지역변수로 인식하게 하여 전역변수보다 우선순위가 높아지게하는 것
즉 인스턴스 자신을 의미하는 키워드 이다.
예제로 확인 해보자

public class fruit{
public string name;
public string color;
public double weigh;
public int count;
public fruit(String name, String color, double weigh, int count){ name=name;
color=color;
weigh=weigh;
count=count;}
public static void main(Stirng[] args){
fruit apple=new fruit("apple","red",100.0,20) ;
System.out.println("name:"+apple.name);
System.out.println("color:"+apple.color);
System.out.println("weigh:"+apple.weigh);
System.out.println("count:"+apple.count); }}

위 예제를 실행하면 null null 0.0 0이 출력 된다.
이는 초기화가 진행되지 않았고 java는 좌측의 name이 fruit 객체의 name 속성을 가리키고있다는 사실을 인지하지 못한다.
따라서 "name = name;"은 "name 매개변수 = name 매개변수"를 의미한다. 이럴때 this 키워드가 사용된다.
아래의 코드를 보자.

public class fruit{
public string name;
public string color;
public double weigh;
public int count;
public fruit(String name, String color, double weigh, int count){ this.name=name;
this.color=color;
this.weigh=weigh;
this.count=count;}
public static void main(Stirng[] args){
fruit apple=new fruit("apple","red",100.0,20) ;
System.out.println("name:"+apple.name);
System.out.println("color:"+apple.color);
System.out.println("weigh:"+apple.weigh);
System.out.println("count:"+apple.count); }}

위 코드를 실행하몀 apple red 100.0 20이 정상적으로 출력된다.
2.같은 클래스에 오버로딩 된 다른 생성자 호출할 때 사용
생성자의 최상단(가장 먼저)에 사용되어야 함
하나의 클래스에 여러개의 생성자가 오버로딩 되어 있을 때
일부분을 제외하고는 서로 중복된 코드를 가지고 있는 경우가 많다.
이런 순간에 내부에 정의된 다른 생성자를 호출해 코드의 중복을 피하고 깔끔한 코드를 작성할 수 있음
생성자를 호출할 때에는 원하는 생성자의 매개변수를 확인한 후 메소드를 호출하는 것처럼 this()의 형태로 이용 예제 사진을 보자
2개의 매개변수를 입력받은 생성자(name, color)의 구현 부분에서 4개의 매개변수를 입력받는 생성자(name, color, weight, count)를 호출하고 있는것을 볼수있다

0개의 댓글