JAVA/Java 기초
this
H_eh
2022. 5. 23. 19:42
this() 는 반드시 생성자의 첫번째 문장에 위치해야한다.
this() 는 반드시 같은 클래스의 다른 생성자를 호출할 때 사용된다.
this() 는 생성자에서만 사용된다.
- 기본생성자가 먼저 실행된다.
- 생성자는 void가 있을 수 없다.
class Book{
String name;
int price;
Book(String name, int price){
this.name=name;
this.price=price;
}
Book(String name){
this(name, 0); //-> 다른생성자 호출
}
Book(){
this("제목미정", 0); //매게변수가 2개이므로 7라인이 호출됨
System.out.println("생성자 호출!");
// show() 실행 이전에 기본생성자(sysout) 먼저 실행됨
}
void show() {
System.out.println(name +" "+ price);
}
}
public class ThisEx1 {
public static void main(String[] args) {
Book b1=new Book("고양이", 30000); //파라미터가 있는 생성자
Book b2=new Book("총균쇠");
Book b3=new Book();
b1.show();
b2.show();
b3.show();
}
}
- 다른 생성자 호출
class Music {
String singer;
String title;
Music(String title, String singer){
this.singer=singer;
this.title=title;
}
Music(String title){
this(title, "방탄"); //다른생성자 호출
}
}
public class Review0524A {
public static void main(String[] args) {
Music m=new Music("On", "BTS");
System.out.println(m.title+ " " +m.singer); // On , BTS 출력
Music m1=new Music("Butter");
System.out.println(m1.title+" " +m1.singer); // Butter, 방탄 출력
}
}
- 생성된 클래스 자신의 주소값 반환
class Person172 {
String name;
int age;
Person172(){
this("이름없음", 1);
}
Person172(String name, int age){
this.name=name; this.age=age;
}
Person172 returnItSelf() { //반환형: 클래스형
return this; //this 반환
}
}
public class Page172 {
public static void main(String[] args) {
Person172 noName = new Person172();
System.out.println(noName.name);
System.out.println(noName.age);
Person172 p = noName.returnItSelf(); //this값을 클래스 변수에 대입
System.out.println(p); //noName.returnItSelf()의 반환값 출력
System.out.println(noName); //참조변수 출력
}
}
728x90
728x90