Java의 'this' 참조

자바에서는 'this'가 현재 객체를 참조하는 참조 변수, 혹은 자바에서는 this가 현재 객체 인스턴스를 참조하는 키워드라고 할 수 있습니다. 현재 클래스 메서드와 필드를 호출하고, 현재 클래스의 인스턴스를 매개변수로 전달하고, 지역 변수와 인스턴스 변수를 구별하는 데 사용할 수 있습니다. 이 참조를 사용하면 코드 가독성이 향상되고 이름 충돌이 줄어들 수 있습니다.

Java 이 참조 예

Java에서 이는 메소드나 생성자가 호출되는 현재 객체를 참조하는 참조 변수입니다. 현재 개체의 인스턴스 변수 및 메서드에 액세스하는 데 사용할 수 있습니다.

다음은 이 참조의 구현입니다.

자바




// Java Program to implement> // Java this reference> // Driver Class> public> class> Person {> > // Fields Declared> > String name;> > int> age;> > // Constructor> > Person(String name,> int> age)> > {> > this> .name = name;> > this> .age = age;> > }> > // Getter for name> > public> String get_name() {> return> name; }> > // Setter for name> > public> void> change_name(String name)> > {> > this> .name = name;> > }> > // Method to Print the Details of> > // the person> > public> void> printDetails()> > {> > System.out.println(> 'Name: '> +> this> .name);> > System.out.println(> 'Age: '> +> this> .age);> > System.out.println();> > }> > // main function> > public> static> void> main(String[] args)> > {> > // Objects Declared> > Person first => new> Person(> 'ABC'> ,> 18> );> > Person second => new> Person(> 'XYZ'> ,> 22> );> > first.printDetails();> > second.printDetails();> > first.change_name(> 'PQR'> );> > System.out.println(> 'Name has been changed to: '> > + first.get_name());> > }> }>

산출

Name: ABC Age: 18 Name: XYZ Age: 22 Name has been changed to: PQR 

설명

위 코드에서는 name과 age라는 두 개의 비공개 필드가 있는 Person 클래스를 정의했습니다. 이 키워드를 사용하여 이러한 필드를 초기화하기 위해 Person 클래스 생성자를 정의했습니다. 또한 이 키워드를 사용하여 현재 개체 인스턴스를 참조하는 이러한 필드에 대한 getter 및 setter 메서드를 정의했습니다.

printDetails() 메소드에서 이 키워드를 사용하여 현재 객체 인스턴스를 참조하고 해당 이름, 연령 및 객체 참조를 인쇄했습니다.

Main 클래스에서는 두 개의 Person 객체를 생성하고 각 객체에 대해 printDetails() 메서드를 호출했습니다. 출력에는 각 개체 인스턴스의 이름, 수명 및 개체 참조가 표시됩니다.

Java에서 'this'를 사용하는 방법

아래에 언급된 Java에서 'this' 키워드를 사용하는 방법은 다음과 같습니다.

  • 현재 클래스 인스턴스 변수를 참조하기 위해 'this' 키워드를 사용합니다.
  • this()를 사용하여 현재 클래스 생성자를 호출합니다.
  • 'this' 키워드를 사용하여 현재 클래스 인스턴스 반환
  • 메소드 매개변수로 'this' 키워드 사용
  • 'this' 키워드를 사용하여 현재 클래스 메서드 호출
  • 생성자 호출에서 'this' 키워드를 인수로 사용

1. 'this' 키워드를 사용하여 현재 클래스 인스턴스 변수 참조

자바




// Java code for using 'this' keyword to> // refer current class instance variables> class> Test {> > int> a;> > int> b;> > // Parameterized constructor> > Test(> int> a,> int> b)> > {> > this> .a = a;> > this> .b = b;> > }> > void> display()> > {> > // Displaying value of variables a and b> > System.out.println(> 'a = '> + a +> ' b = '> + b);> > }> > public> static> void> main(String[] args)> > {> > Test object => new> Test(> 10> ,> 20> );> > object.display();> > }> }>

산출

a = 10 b = 20 

2. this()를 사용하여 현재 클래스 생성자를 호출합니다.

자바




// Java code for using this() to> // invoke current class constructor> class> Test {> > int> a;> > int> b;> > // Default constructor> > Test()> > {> > this> (> 10> ,> 20> );> > System.out.println(> > 'Inside default constructor '> );> > }> > // Parameterized constructor> > Test(> int> a,> int> b)> > {> > this> .a = a;> > this> .b = b;> > System.out.println(> > 'Inside parameterized constructor'> );> > }> > public> static> void> main(String[] args)> > {> > Test object => new> Test();> > }> }>

산출

Inside parameterized constructor Inside default constructor 

3. 'this' 키워드를 사용하여 현재 클래스 인스턴스 반환

자바




// Java code for using 'this' keyword> // to return the current class instance> class> Test {> > int> a;> > int> b;> > // Default constructor> > Test()> > {> > a => 10> ;> > b => 20> ;> > }> > // Method that returns current class instance> > Test get() {> return> this> ; }> > // Displaying value of variables a and b> > void> display()> > {> > System.out.println(> 'a = '> + a +> ' b = '> + b);> > }> > public> static> void> main(String[] args)> > {> > Test object => new> Test();> > object.get().display();> > }> }>

산출

a = 10 b = 20 

4. 'this' 키워드를 메소드 매개변수로 사용

자바




// Java code for using 'this'> // keyword as method parameter> class> Test {> > int> a;> > int> b;> > // Default constructor> > Test()> > {> > a => 10> ;> > b => 20> ;> > }> > // Method that receives 'this' keyword as parameter> > void> display(Test obj)> > {> > System.out.println(> 'a = '> + obj.a> > +> ' b = '> + obj.b);> > }> > // Method that returns current class instance> > void> get() { display(> this> ); }> > // main function> > public> static> void> main(String[] args)> > {> > Test object => new> Test();> > object.get();> > }> }>

산출

a = 10 b = 20 

5. 'this' 키워드를 사용하여 현재 클래스 메서드 호출

자바




// Java code for using this to invoke current> // class method> class> Test {> > void> display()> > {> > // calling function show()> > this> .show();> > System.out.println(> 'Inside display function'> );> > }> > void> show()> > {> > System.out.println(> 'Inside show function'> );> > }> > public> static> void> main(String args[])> > {> > Test t1 => new> Test();> > t1.display();> > }> }>

산출

Inside show function Inside display function 

6. 생성자 호출에서 'this' 키워드를 인수로 사용

자바




// Java code for using this as an argument in constructor> // call> // Class with object of Class B as its data member> class> A {> > B obj;> > // Parameterized constructor with object of B> > // as a parameter> > A(B obj)> > {> > this> .obj = obj;> > // calling display method of class B> > obj.display();> > }> }> class> B {> > int> x => 5> ;> > // Default Constructor that create an object of A> > // with passing this as an argument in the> > // constructor> > B() { A obj => new> A(> this> ); }> > // method to show value of x> > void> display()> > {> > System.out.println(> 'Value of x in Class B : '> + x);> > }> > public> static> void> main(String[] args)> > {> > B obj => new> B();> > }> }>

산출

Value of x in Class B : 5 

'this' 참조 사용의 장점

아래에 언급된 것처럼 Java에서 'this' 참조를 사용하면 몇 가지 이점이 있습니다.

  1. 이는 동일한 이름을 가진 인스턴스 변수와 지역 변수를 구별하는 데 도움이 됩니다.
  2. 현재 개체를 다른 메서드에 인수로 전달하는 데 사용할 수 있습니다.
  3. 메소드에서 현재 객체를 반환하는 데 사용할 수 있습니다.
  4. 동일한 클래스의 다른 오버로드된 생성자에서 생성자를 호출하는 데 사용할 수 있습니다.

'this' 참조 사용의 단점

'이' 참조에는 많은 장점이 있지만 다음과 같은 단점도 있습니다.

  1. 이를 과도하게 사용하면 코드를 읽고 이해하기가 더 어려워질 수 있습니다.
  2. 이것을 불필요하게 사용하면 프로그램에 불필요한 오버헤드가 추가될 수 있습니다.
  3. 이를 정적 컨텍스트에서 사용하면 컴파일 시간 오류가 발생합니다.
  4. 전반적으로 이 키워드는 Java의 객체 작업에 유용한 도구이지만 필요한 경우에만 신중하게 사용해야 합니다.

이 기사는 기고자: 메학나랑 그리고 아밋 쿠마르 .