안녕하세요!! 오늘은 자바에서 생성자 This 활용하는법을 알아보도록 하겠습니다!!
생성자This 는 같은 기능을 하는 생성자 사이에서 코드의 간결함과 유지보수의 편리함을위해 사용하는데요.
아래 예를보고 알아보겠습니다.
public class ThisTest {
private int a;
private int b;
ThisTest(){
a = b;
}
ThisTest(int a){
this.a = a;
b = 0;
}
ThisTest(int a, int b){
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public static void main(String[] args) {
ThisTest t1 = new ThisTest();
ThisTest t2 = new ThisTest(10);
ThisTest t3 = new ThisTest(30,40);
System.out.println(t1.getA()+"\t"+t1.getB());
System.out.println(t2.getA()+"\t"+t2.getB());
System.out.println(t3.getA()+"\t"+t3.getB());
}
}
public class ThisTest {
private int a;
private int b;
ThisTest(){
this(0,0);
}
ThisTest(int a){
this(a,0);
}
ThisTest(int a, int b){
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public static void main(String[] args) {
ThisTest t1 = new ThisTest();
ThisTest t2 = new ThisTest(10);
ThisTest t3 = new ThisTest(30,40);
System.out.println(t1.getA()+"\t"+t1.getB());
System.out.println(t2.getA()+"\t"+t2.getB());
System.out.println(t3.getA()+"\t"+t3.getB());
}
}
위코드와 아래코드의 결과는 같습니다.두 코드의 차이점이 보이시나요??
위 코드는 생성자간에 비슷한 동작을 하는 코드를 넣었고 아래는 this를 이용하여 만들었습니다!
뭐가 정답이라고 할순없지만 이렇게 사용할수 있다는 것을 알고 간다면 언젠가 도움이 될수도 있겠죠?.
감사합니다.