package kr.s15.object.thistest;
public class ThisMain01 {
//생성자
public ThisMain01() {
//this는 객체 내부에서 객체를 지칭할 때 사용할 수 있고 일종의
//참조 변수 역할을 함.
//객체의 구성원(필드,메서드)을 호출할 때 사용
System.out.println("객체생성 :" +this);
}
public static void main(String[] args) {
ThisMain01 tm = new ThisMain01();
System.out.println("객체 생성 후 :"+ tm);
//둘 다 같은 위치를 나타냄
}
}
객체생성 :kr.s15.object.thistest.ThisMain01@1ee0005
객체 생성 후 :kr.s15.object.thistest.ThisMain01@1ee0005
package kr.s15.object.thistest;
/*
class ThisTest{
//은닉화
private int a;//멤버 변수
//캡슐화
public void setA(int a) { //지역변수 a
a = a;
//지역변수 = 지역변수 로 인식 why? 멤버변수와 이름이 같기 때문에. 이름이 같으면 지역변수가 우선시됨.
}
public int getA() {
return a;
}
}
*/
class ThisTest{
//은닉화
private int a;//멤버 변수
//캡슐화
public void setA(int a) { //지역변수 a
// 멤버변수 = 지역변수
this.a = a; //this를 쓰면 a가 지역변수에서 멤버변수로 변경됨
}
public int getA() {
return a;
}
}
public class ThisMain02 {
public static void main(String[] args) {
ThisTest tt = new ThisTest();
tt.setA(10);
System.out.println(tt.getA());
}
}
10
package kr.s15.object.thistest;
public class ThisMain03 {
//생성자
public ThisMain03() {
/*
* 생성자 내부에서 또 다른 생성자를 호출 할 때 this()를 사용한다.
* 반복적인 코드를 제거하고 코드를 재사용하기 위해 또다른 생성자를
* 호출해서 동작시킴
*/
//System.out.println("-----"); //this() 전에 코드를 쓰면 에러가 난다.
this("여름");//생성자 안에서 또다른 생성자를 호출할 때 사용
System.out.println("~~~~~~~");
}
public ThisMain03(String msg) {
System.out.println(msg);
}
public ThisMain03(int a) {
this(String.valueOf(a)); //valueOf 는 static이기 때문에 String.valueOf을 사용
} //글씨가 이탈리안식처럼 기울어있으면 static임
public static void main(String[] args) {
ThisMain03 tm = new ThisMain03();
ThisMain03 tm2 = new ThisMain03("겨울");
ThisMain03 tm3 = new ThisMain03(50000);
}
}
여름
~~~~~~~
겨울
50000