ocjap를 위한 자바 기초/oca
[ocjap] 생성자 Constructor
xemaker
2020. 5. 29. 13:51
public class BirdSeed {
private int numberBags;
boolean call;
public BirdSeed() {
// LINE 1
call=false;
// LINE 2
}
public BirdSeed(int numberBags) {
this.numberBags=numberBags;
System.out.println("파리미터 생성자 호출됨");
}
public static void main(String[] args) {
BirdSeed seed = new BirdSeed();
System.out.println(seed.numberBags);
}
}
Which code can be inserted to have the code print 2?
A) Replace line 2 with new BirdSeed(2);
B) Replace line 1 with this(2);
C) Replace line 1 with new BirdSeed(2);
D) Replace line 1 with BirdSeed(2);
E) Replace line 2 with BirdSeed(2);
F) Replace line 2 with this(2);
생성자는 new 없이 호출할 수 없기 때문에 D와 E는 컴파일 오류.
A와 C는 컴파일이 되지만 여기에 필드를 세팅하는게 아니라 새로운 객체를 생성해버린다.
F는 컴파일이 되나 this()는 생성자의 첫번째 라인에 있어야 한다.
B는 맞다.
정답: B