this는 heap 변수를 의미한다.
생성자는 객체를 초기화할 때 사용한다.
기본생성자
생성자: 객체가 생성될 때 객체를 초기화 시켜주는 메서드
new : heap에 저장, Bugger() : 생성자 메서드 실행
package ex04;
class Bugger {
private String name;
private int price;
// 생성자 - 컴파일시 jvm이 생성자를 만들어 준다.
public Bugger(String n, int p) {
name = n;
price = p;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
public class BuggerTest {
public static void main(String[] args) {
Bugger b1 = new Bugger("기본버거", 2000);
System.out.println(b1.getName());
System.out.println(b1.getPrice());
/*System.out.println(b1.name);
System.out.println(b1.price);*/
}
}
1. 생성자 메서드가 없으면 자동으로 기본 생성자 메서드가 호출된다.(변수의 타입에 맞는 데이터로 자동 초기화 해준다)
package ex04;
class Box {
int width;
int height;
int depth;
}
public class BoxTest {
public static void main(String[] args) {
Box b = new Box(); // 생성자 함수가 타입에 맞는 변수로 초기화 해준다. width == 0, height == 0, depth == 0
System.out.println("상자의 크기: (" + b.width + "," + b.height + "," + b.depth + ")");
}
}
2. 기본 생성자가 추가되지 않는 경우
package ex04;
class Box {
int width;
int height;
int depth;
public Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
}
public class BoxTest {
public static void main(String[] args) {
Box b = new Box(); // 오류 발생
System.out.println("상자의 크기: (" + b.width + "," + b.height + "," + b.depth + ")");
}
}
개발자가 생성자를 선언하면 컴파일러는 자동으로 생성자를 만들어 주지 않는다.
선언한 생성자는 인수를 3개 받는데 new로 생성할때 인자를 넣지 않아 오류가 발생
생성자 this 의미
this는 현재 객체 자신을 가리키는 참조 변수다.
this는 컴파일러에서 자동으로 생성한다.
class Car {
int wheel;
public Car(int wheel) {
wheel = wheel;
}
}
위와 같이 같은 이름을 사용하면 컴파일러는 생성자 메서드에 있는 wheel 이라고 생각한다.
Variable 'wheel' is assigned to itself → 자기 자신에게 할당되었다고 경고가 뜬다.
class Car {
int wheel;
public Car(int wheel) {
this.wheel = wheel;
}
}
this가 현재 객체를 참조(객체의 주소)하고 있다.(가리키고 있다) 따라서, 객체에 있는 wheel값에 인자로 받은 wheel값을 할당하는 것이다.
이름이 같을 때는 객체에 존재하는 변수라고 this를 붙여 사용하는 것이다.
1. 텔레비전 클래스 작성하고 객체 생성해보기
package ex04;
public class Television {
int channel;
int volume;
boolean onOff;
public static void main(String[] args) {
Television tv = new Television();
tv.onOff = true;
tv.volume = 50;
tv.channel = 36;
Television tv2 = new Television();
tv2.onOff = true;
tv2.volume = 30;
tv2.channel = 10;
System.out.println("첫 번째 텔레비젼의 채널은 " + tv.channel + " 이고 볼륨은 " + tv.volume + " 입니다.");
System.out.println("두 번째 텔레비젼의 채널은 " + tv2.channel + " 이고 볼륨은 " + tv2.volume + " 입니다.");
}
}
2. 생성자 만들어 보기
package ex04;
class Television {
int channel;
int volume;
boolean onOff;
public Television(int c, int v, boolean o) {
channel = c;
volume = v;
onOff = o;
}
public void print() {
System.out.println("채널은 " + channel + "이고 볼륨은" + volume + " 입니다.");
}
}
public class TelevisionTest {
public static void main(String[] args) {
Television tv = new Television(36, 50, true);
tv.print();
Television tv2 = new Television(10, 30, true);
tv2.print();
}
}
Share article