본문 바로가기
국비지원/JAVA

[JAVA] 13-3. this keyword

by cosmog 2022. 10. 7.
반응형
this
  • parmeter(매개변수)값에 멤버변수 이름을 그대로 사용하고 싶을 때 this 사용.(자바 언어의 특징.)
  • this.멤버변수 = parameter이름(멤버변수이름과 동일하게); 사용가능
  • this = 나의 주소가 나온다.
  • <문법> - this. 과 this()뿐이다. (this.멤버변수 or this.method & this()은 생성자를 지칭한다.)

    * 주로 자기자신의 생성자에서 많이 사용한다.
    * 생성자는 상속이 안된다. 나 자신의 고유한것.

 

Quiz - 달리는 차 만들기(this를 사용하여 생성자 만들기)

 

🔆 main 클래스

package day13.this_Q;

public class Main {
	
	public static void main(String[] args) {
		
		Car car = new Car("casper");
		
		car.run();
	}

}

🔆 Car 클래스

package day13.this_Q;

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