본문 바로가기

수업 복습하기/Java

Day 11 - this() & this.

728x90
728x90

=  this() & this.

 

생성자 오버로딩이 많을 떄, 중복된 코드 발견을 줄이기 위해서 생성자에서 다른 생성자를 호출 할 떄 사용하는 것.

this.를 사용하면 동일 클래스 내의 멤버(멤버변수, 메서드)를 참조 할 수 있습니다.

this()을 사용하면 생성자 내부에서 자신의 다른 생성자를 호출 할 수 있습니다.

this()는 반드시 생성자의 첫줄에서 사용해야한다.

 

바로 예시 확인하기

 

<정답>

누구로 생성하던 이문장을 실행
이름:홍길동, 나이:10, 학번:20001212

 

<해설>

< Person >
package this_.basic;

public class Person {
	String name;
	int age;
	
	Person(String name, int age){
		this.name = name; //멤버변수 접근 어려움
		this.age = age;
	System.out.println("누구로 생성하던 이문장을 실행");
	}
	
	Person(String name){
		this(name,1);
//		this.name=name;
//		this.age=1;
	}
	
	Person(){
		this("이름미정",1);
//		this.name="이름미정";
//		this.age=1;
	}
	
	String info() {
		return "이름:"+this.name+", 나이:"+this.age;
	}
}
< MainClass >
package this_.basic;

public class MainClass {
public static void main(String[] args) {
	
	Student s = new Student("홍길동",10,"20001212");
	System.out.println(s.info());
	}
}

728x90