public class constructor_review
{
private int num;
constructor_review()
{
num =100;
}
constructor_review(int num)
{
this(); //기본생성자를 호출
num = num+ num;
}
public int getRollNum()
{
return num;
}
public static void main(String args[])
{
constructor_review obj = new constructor_review(55);
System.out.println(obj.getRollNum());
}
}
위의 코드를 출력값이 155가 되도록 수정
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
30
|
package week_FOUR;
public class constructor_review
{
private int num;
constructor_review(){
num = 100;
}
constructor_review(int num){
this();
this.num = this.num + num;
}
public int getRollNum(){
return num;
}
public static void main(String args[]){
constructor_review obj = new constructor_review(55);
System.out.println(obj.getRollNum());
}
}
|
cs |
obj(55) -> constructor_review(int num) 호출
constructor_review(int num) , num = 55;
this(); -> 1. constructor_review, num = 100
num에는 100이 담기게 된다.
이때, num = num + num; 으로 코드를 실행하면 num에는 결국 55+55 =110이 담기게 된다.
따라서 this.num = this.num + num 으로 수정을 해주어야 함.
num = 155가 담기므로 getRollNum을 호출하면 155가 출력됨.
'Language > JAVA' 카테고리의 다른 글
완전탐색 (0) | 2021.10.03 |
---|---|
객체 배열 (0) | 2021.09.28 |
객체 배열 / 추상화 (0) | 2021.08.31 |
다형성(오버라이드,오버로드)/객체 형변환/암묵적 형변환 (0) | 2021.08.08 |
클래스, getter그리고setter, 접근한정자 (0) | 2021.08.01 |