1. this

 

- 객체 자신을 의미(객체자신의 주소값)

 

- this의 용도

1) 멤버변수와 매개변수의 이름이 같을때 멤버변수앞에 this를 붙여서 구분
2) 다른 생성자를 호출할때
3) 객체자신을 메소드의 파라미터로 보낼때

 

ex>

class MyUser
{
    private String id;
    private String pwd;

 

    //다른 생성자 호출
    public MyUser(){
        this("admin","0000");
    }
    //멤버변수와 매개변수의 이름이 같을때 
    public MyUser(String id,String pwd)
    {
        this.id=id;
        this.pwd=pwd;
    }
    public void print(){
        System.out.println("아이디:"+id+",비밀번호:"+pwd);
    }
}
class  Test01_this
{
    public static void main(String[] args)
    {
        MyUser user1=new MyUser();
        user1.print();

        MyUser user2=new MyUser("song","1234");
        user2.print();
    }
}

 

ex>

class MyRect
{
    private String color;
    private int x,y;

    public MyRect(String color,int x,int y)
    {
        this.color=color;
        this.x=x;this.y=y;
    }
    public String getColor(){
        return color;
    }
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    //객체자신을 메소드의 파라미터로 보낼때
    public void print(){
        Printer.prtPrint(this);
    }
}
class Printer
{
    public static void prtPrint(MyRect mr){
        System.out.println("프린터로 아래의 정보를 갖는 사각형을 출력");
        System.out.println("x:"+mr.getX() +",y:"+mr.getY()+",색상:"+ mr.getColor());
    }
}
class Test02_this
{
    public static void main(String[] args)
    {
        MyRect rr=new MyRect("빨강",100,200);
        rr.print();
    }   
}

 

 

 

 

 

'JAVA' 카테고리의 다른 글

오버라이딩 / final의 용도  (0) 2014.09.12
상속  (0) 2014.09.12
객체배열  (0) 2014.09.12
static  (0) 2014.09.12
final  (0) 2014.09.12

+ Recent posts