자바에서 인자전달을 단순 this만 사용하는 문법
조회수 2248회
안녕하세요 자바 문법중 이해가 가지 않는 것이 있어 올립니다.
예)
GoogleApiClient gac = new GoogleApiClient.Builder(this, this, this)
.addApi(Games.API)
.build();
위와같이 this를 인자로 전달하는 경우가 문법적으로 어떻게 이해가 안가서 문의드려요
this.매개변수 : 자기 자신 매개변수의 값을 지칭 함 this(): 자기 자신의 생성자를 호출함
단순 this만을 이용해서 인자를 전달하는게 좀 생소해서요
쉽게 이해할만 예제 소스나 설명 주시면 감사하겠습니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
간단하게 예제 소스를 작성해봤습니다.
@Test 붙어 있는 부분이 시작점입니다. 메인메서드라고 생각하시면 됩니다.
public class ExampleClass { private String className = "ExampleClass"; public String getClassName() { return className; } @Test public void startPotnt() throws Exception { TestClass testClass = new TestClass(this); /* this 는 자기 자신의 객체를 가르킨다고 보면 됩니다. this 로 TestClass 생성자에 ExampleClass 의 객체를 전달했으니, TestClass 생성자에서는 ExampleClass 타입으로 받아야함 */ } } class TestClass { private String className; public TestClass(ExampleClass exampleClass) { String className= exampleClass.getClassName(); this.className= className; System.out.println(this.className); // ExampleClass /* 현재 TestClass에서 className 은 1. TestClass 의 className 멤버 변수와 2. exampleClass.getClassName(); 의 값을 저장한 className 지역 변수 두개입니다. 이 둘을 구분하기위해 자기 자신의 객체를 가르키는 this 를 사용하여 this.className(TestClass 멤버변수를 가르킴)에 className(지역변수)의 값을 저장한 것 입니다. */ } }
댓글 입력