← Quiz: Java Classes and Objects: all 10 questions
Quiz: Java Classes and Objects · Question 6 of 10
What does this print? (code)
What does this print?
class Box {
int w, h;
Box() {
this(5);
h++;
}
Box(int w) {
this.w = w;
h = w;
}
}
public class Main {
public static void main(String[] args) {
Box b = new Box();
System.out.println(b.w + " " + b.h);
}
}
- A.0 1
- B.5 5
- C.5 6
- D.6 6
Answer & explanation
Correct answer: 5 6
this(5) runs the other constructor first (w = 5, h = 5); then the rest of Box() adds 1 to h.
Can you get the rest right without peeking?
Take the timed Quiz: Java Classes and Objects quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →