this

1) 메서드의 매개변수와 멤버변수 명이 같을때  멤버변수 앞에 붙인다 (컴퓨터가 인식 x)

    this.멤버변수=매개변수

ex) public void setName(String name){
		this.name=name;
	}

 

2) 현재 생성된 객체를 가리키는 예약어(키워드) 

생성자 내부에서 같은 클래스 객체명을 사용하지 않는다.

 

this 예약어로 대신 사용

public class ThisTest2 {
	private int a=100;

	ThisTest2(int a){
		this.a = a;
		System.out.println("현재 생성된 객체이름?: "+this);
		//tt2객체의 또 다른 이름(동의어임)
	}
	
	public int getA() {
		return a;//생성된 객체의 int a값 
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThisTest2 tt2 = new ThisTest2(200);
		//같은 객체라면 주소값이 같다
		System.out.println("tt2의 주소값: "+tt2);
		System.out.println("tt2.getA(): "+tt2.getA());
		System.out.println("------------------------------");
		
		ThisTest2 tt3 = new ThisTest2(300);
		System.out.println("tt3의 주소값: "+tt3);
		System.out.println("현재 생성된 객체이름(tt3)=>"+tt3.getA());
	}
}
/*
현재 생성된 객체이름?: j210107.ThisTest2@15db9742
tt2의 주소값: j210107.ThisTest2@15db9742
tt2.getA(): 200
------------------------------
현재 생성된 객체이름?: j210107.ThisTest2@6d06d69c
tt3의 주소값: j210107.ThisTest2@6d06d69c
tt3.getA()300
*/

 


예시)

class Rect{
	private int x,y;
	Rect(){ 
		//System.out.println("기본생성자");
		//생성자에서 다른 생성자 호출시 반드시 첫번째 문장이어야한다.
		this(10,10); //초기값 10,10으로 설정
	}
	Rect(int x){//오버로딩:매개변수 갯수,자료형으로 구분하는데
		        //이때, 자료형이 같고 매개변수의 갯수가 같으면 식별이 불가능하다. 
		y=10; //기본값 y=10
	    setX(x);
	}
	Rect(int x, int y){
		this.x=x;
		this.y=y;
	}
	
	public void setX(int x) {
		if(x<0) {
			System.out.println("x값은 음수입력불가");
			this.x=10;
			return;
		}
		this.x=x;
	}
	public void setY(int y) {
		if(y<=0) {
			System.out.println("y값은 음수입력불가");
		}else {
		   this.y=y;
		}
	}
	public int getX() { return this.x;}
	public int getY() { return this.y;}
	void area() {
	  System.out.println("x= "+x+",y= "+y+
			  "\n입력받은 직사각형의 면적은(x*y)의 값은"+(x*y));
	}
}
public class HWRectHandling {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
      Rect r1=new Rect();
      r1.area();
      Rect r2=new Rect(20);
      r2.area();
      Rect r3=new Rect(20,20);
      r3.area();
	}
}
/*
x= 10,y= 10
입력받은 직사각형의 면적은(x*y)의 값은100
x= 20,y= 10
입력받은 직사각형의 면적은(x*y)의 값은200
x= 20,y= 20
입력받은 직사각형의 면적은(x*y)의 값은400
*/

+ Recent posts