this는 왜 쓰는 것일까 < > super() 부모소환!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class Student99 {
private String name;
private int korean;
private int english;
private int math;
public Student99(String name, int korean, int english, int math) {
// this.name=name;
// this.korean=korean;
// this.english=english;
// this.math=math;
}
void stat(int english, int math) {
System.out.println(name+", "+korean+", "+english+", "+math);
}
}
public class A08_Practice {
public static void main(String [] args) {
Student99 st4 = new Student99("방울이",100,50,70);
st4.stat(5, 7);
}
}
|
cs |
this가 없는 경우 어떻게 될까
출력 값은 null, 0, 5, 7로 이름과 국어 값에 "방울이 와 100"이 아닌 "null과 0" 이 나왔다.
line 25에서 Student99를 불러올 때 "방울이",100,50,70 을 넣었으나
line 7의 지역변수에 넣은 것일 뿐 line 12의 }를 나가는 순간 무쓸모다.
그래서 stat 메서드를 불러왔을 때 null과 0이 나온 것이다.
아하! this를 통해서 "방울이",100,50,70 값을 전역 변수인 필드에 넣어 전역에 영향을 주기 위함이구나.
따라서 외부 클래스를 불러오기 위해 new생성자를 쓸 때, 또는 클래스에서 생성자를 통해 초기화할 때
옆에 적는 것들(arguments)
그곳에는 전역에 영향을 미치는 값을 써야 한다. 어떠한 메서드를 써도 유용이 쓰이며 변하지 않는 값들.
물론 때에 따라 메서드에서 값을 덮어쓸 수 있다.
변하지 않는 것들....
'JAVA > 되새김질' 카테고리의 다른 글
메서드 특징!? 아니 내가 몰랐던 것 (0) | 2019.08.18 |
---|---|
객체지향 복습(3) ─1:1 (Obj vs Obj) + 객체 사용 (0) | 2019.08.17 |
야구 스코어 만들기 (0) | 2019.08.16 |
객체지향 복습(2) ─ 클래스 선언, 필드 사용방법, 접근제어자 (0) | 2019.08.15 |
객체지향 복습(1) ─ 참조변수, 닷, this, overloading (0) | 2019.08.14 |