본문 바로가기
IT/JAVA

JAVA - 예제 - this

by 비준 2023. 6. 12.

1. 예제

 -> this를 사용해보자

 

2. 코드

//예제 1

package java_learn;

class A {
void method(){
System.out.println(this);
}
}
public class java1 {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();

a1.method(); //this는 자기자신의 주소값을 가지고 있는 것
System.out.println(a1); //위의 출력 값과 값이 같은 것을 알 수 있다.
}
}

 

//예제 2

package java_learn;

class B { //클래스
int num; //멤버 변수
void printNum() { //멤버 메소드 선언
  System.out.println("num >>" + this.num); //this가 자기자신의 주소에 가서 num를 가지고 오라고 한것
System.out.println("참조값 >> " + this);
}
}
public class java1 {
public static void main(String[] args) {
B b1 = new B();
B b2 = new B();

b1.num = 10;
b2.num = 20;

b1.printNum();
b2.printNum();
}
}

댓글