java에서this의 용법 예시 (키워드this)
예제 코드: TestThis_1.java
/* : this
* :
* A@4e44ac6a
*/
public class TestThis_1 {
public static void main(String[] args) {
A aa = new A();
System.out.println(aa.f()); //aa.f(), aa ( )
}
}
class A {
public A f() {
return this; // f() A
}
}
this의 흔한 용법1. 같은 이름의 변수 구분
예제 코드: TestThis_2.java
/* this 1:
* :
* this. i = 1
* i = 33
*/
public class TestThis_2 {
public static void main(String[] args) {
A aa = new A(33);
}
}
class A {
public int i = 1; // i
/* : , , */
public A(int i) { // i
System.out.printf("this. i = %d
", this.i); //this.i i
System.out.printf("i = %d
", i); // i i
}
}
2. 구조 방법 간의 상호 호출예제 코드: TestThis_3.java
/* this 2: */
public class TestThis_3 {
public static void main(String[] args) {
}
}
class A {
int i, j, k;
public A(int i) {
this.i = i;
}
public A(int i, int j) {
/* i = 3; error : this(...) ,
* TestThis_3.java:20: error: call to this must be first statement in constructor
* this(i);
* ^
* 1 error
*/
this(i);
this.j = j;
}
public A(int i, int j, int k) {
this(i, j);
this.k = k;
}
}
주의사항static에 수식되는 방법은this바늘이 없습니다.static에 수식되는 방법은 공공적이기 때문에 어떤 구체적인 대상에 속한다고 말할 수 없다.
예제 코드: TestThis_4.java
/*static this */
public class TestThis_4 {
public static void main(String[] args) {
}
}
class A {
static A f() {
return this;
/* :TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
* return this;
* ^
* 1 error
*/
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
38. Java의 Leetcode 솔루션텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.