본문 바로가기
JAVA

221007 this

this-this., this()
this는 자기 자신 객체를 지정할 때 사용하는 키워드입니다
this.을 사용하면 "동일 클래스" 내의 "멤버(멤버변수, 메서드)"를 참조할 수 있다.
this()를 사용하면 같은 클래스 안의 생성자 내부에서 자신의 다른 "생성자"를 호출할 수 있다.

class명
String name;
int age;

Person(String name, int age){
	name = name;
	age = age;
}



자바 특징-변수는 나랑 가장 가까운 변수를 참조한다.
-this는 컴퓨터가 알아먹게 해주는 키워드
위의 경우 메서드안에서 매개변수만 사용된 상태.
이렇게 겹칠 때 this.(->멤버변수)을 사용함.

this()를 사용할 때는 생성자의 연결.

this()는 나의 생성자를 의미함
생성자 안에서 특정 생성자로 연결함

 

eclipse Car -this 실습

package quiz08;

public class Car {
	
	String model;
	int speed;
	
	//1. model을 전달받아서 model에 저장하는 생성자를 생성하세요
	Car(String model){
		this.model=model;
	}
	
	
	void accel(int speed) {
		/*
		멤버변수 speed가 150 이상이라면 "속도를 올릴 수 없습니다" 를 출력
		그렇지 않으면 매개변수를 멤버변수에 저장하세요
		*/
		if(this.speed>=150) {
			System.out.println("속도를 올릴 수 없습니다");
		} else{
			this.speed=speed;
		}

	}
	
	void run() {
		/*	
		0-200 까지 30씩 증가하는 for문을 생성하고, 
		for문안에서 accel()를 호출하세요
		멤버변수 speed도 출력하세요
		*/
		for(int i=0;i<=200;i+=30) {
			this.accel(i);
			System.out.println(this.speed);
		}
		
	}
}

 

Main

package quiz08;

public class CarMain {
	public static void main(String[] args) {
		
		
		Car c = new Car("쿠페");
		
		c.run();
		
		
	}

}
0
30
60
90
120
150
속도를 올릴 수 없습니다
150