1Z0-811 · Question #13
Given the code fragment: class Ball { double weight; } public class App { public static void main (String[] args) { //line n1 } } Which code fragment can be inserted at line n1 to enable the code to…
The correct answer is D. Ball b = new Ball(). Option D works because Java automatically provides a default no-argument constructor when no constructor is explicitly defined. When new Ball() is called, the instance field weight (a double) is automatically initialized to 0.0 - Java's default value for all double fields…
Question
Options
- ABall b = null; b.weight = 0.0;
- BBall.weight = 0.0;
- CBall b = new Ball(0.0);
- DBall b = new Ball();
How the community answered
(18 responses)- C6% (1)
- D94% (17)
Explanation
Option D works because Java automatically provides a default no-argument constructor when no constructor is explicitly defined. When new Ball() is called, the instance field weight (a double) is automatically initialized to 0.0 - Java's default value for all double fields - making it printable.
Why the distractors fail:
- A declares
basnullthen immediately dereferences it (b.weight), causing aNullPointerExceptionat runtime - nothing prints. - B treats
weightas a static field usingBall.weight, but it's an instance field; this is a compile error. - C calls
new Ball(0.0), but no constructor accepting adoubleexists inBall; this is also a compile error.
Memory tip: When a Java class has no explicit constructor, the compiler silently adds one - ClassName() with no args. Primitive instance fields (int, double, boolean, etc.) always get zero-equivalent defaults (0, 0.0, false) upon object creation. If you see new ClassName() with no args and no constructor defined, it compiles and zeroes out the fields.
Topics
Community Discussion
No community discussion yet for this question.