Cute Blinking Unicorn

백엔드/JAVA

객체 자신을 가리키는 참조변수 - this

민밥통 2023. 10. 24. 10:52

this : 객체의 메소드 내부에서만 사용 가능하다. 

인스턴스 자신을 가리키는 참조변수,

인스턴스의 주소가 저장되어 있다.

 this(), this(매개변수) 생성자, 같은 클래스의 다른 생성자를 호출할 때 사용한다.

 

public class Ex6_13 {

public static void main(String[] args) { //메인도 메서드

package myproject;

 

class Car2 {

String color; // 색상

String gearType; // 변속기 종류 = auto (자동), manual (수동)

int door; // 문의 개수

 

Car2() { //기본생성자

//this(): 자신 객체 생성 > 생성자 호출

this("white", "auto", 4); //메소드가 속해있는 객체의 주소

System.out.println("안녕하세요");

 

}

 

Car2(String color) { //인수 생성자 , 메서드

 

this(color, "auto", 4);

}

 

Car2(String color, String gearType, int door) { //함수가 여러개 있는 특징은 메서드 오버로딩

// 어떤 함수를 호출의 기준? 매개변수의 개수나 자료형 or 조건

this.color = color;

this.gearType = gearType;

this.door = door;

}

}

public class Ex6_13 {

public static void main(String[] args) {

Car2 c1 = new Car2(); //기본생성자

Car2 c2 = new Car2("blue"); //인수 생성자

 

System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);

System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);

}

}

안녕하세요

c1의 color=white, gearType=auto, door=4

c2의 color=blue, gearType=auto, door=4