2013년 9월 17일 화요일

[자바7, JDK1.7강좌, 자바교육, JAVA7강좌]자바에서 this란(java this) 1. this란? 메소드 내에서만 사용 가능하고 메소드가 속하는 객체 자신의...

[자바7, JDK1.7강좌, 자바교육, JAVA7강좌]자바에서 this란(java this)
1. this란?
메소드 내에서만 사용 가능하고 메소드가 속하는 객체 자신의 참조 값을 가짐
2. 용도

은닉된 이름을 사용
public void setRadius( double radius ) {
    this.radius = radius;
}
자신의 객체 참조값을 다른 객체의 메쏘드에 전달
obj.someOtherMethod( this );
자신의 객체 참조값을 반환
return this;
class Circle
{
    private double radius = 0;
    public Circle setRadius( double radius ) {
        this.radius = radius;
        return this;  //자기자신 객체의 참조를 리턴, 리턴형은 Circle이므로 가능
    }
    public double getArea() {
        return Math.PI * radius * radius;
    }
    public Circle display() {
        System.out.println("Areas of circle with radius " +
            radius + " = " + getArea() );
        return this;
    }
}

class ThisTest
{
    public static void main( String args[] )
    {
        Circle circle1 = new Circle();
       
        //circle1.setRadius(3)의 리턴형이 Circle의 인스턴스 이므로 .display() 가능
        (((circle1.setRadius(2)).display()).setRadius(2)).display();
        circle1.setRadius(2).display().setRadius(2).display();
    }
}

[결과]
Areas of circle with radius 2.0 = 12.566370614359172
Areas of circle with radius 2.0 = 12.566370614359172
Areas of circle with radius 2.0 = 12.566370614359172
Areas of circle with radius 2.0 = 12.566370614359172


오라클자바커뮤니티에서 설립한 개발자교육6년차 오엔제이프로그래밍 실무교육센터
(오라클SQL,튜닝,힌트,자바프레임워크,안드로이드,아이폰,닷넷 실무개발강의)  


[개강확정 강좌]




댓글 없음:

댓글 쓰기