1Z0-809 · Question #48
Given: 1. abstract class Shape { 2. Shape ( ) { System.out.println ("Shape"); } 3. protected void area ( ) { System.out.println ("Shape"); } 4. } 5. 6. class Square extends Shape { 7. int side; 8…
The correct answer is D. At line 17, insert super (x); F. At line 20, use public void area () {. D is correct because Rectangle extends Square, and Square defines only a parameterized constructor Square(int side) - meaning Java does not auto-generate a no-arg constructor. Without an explicit super(x) call, Rectangle's constructor would try to invoke a non-existent…
Question
- abstract class Shape {
- Shape ( ) { System.out.println ("Shape"); }
- protected void area ( ) { System.out.println ("Shape"); }
- }
- class Square extends Shape {
- int side;
- Square (int side) {
- /* insert code here */
- this.side = side;
- }
- public void area ( ) { System.out.println ("Square"); }
- }
- class Rectangle extends Square {
- int len, br;
- Rectangle (int x, int y) {
- /* insert code here */
- len = x; br = y;
- }
- void area ( ) { System.out.println ("Rectangle"); }
- } Which two modifications enable the code to compile?
Options
- AAt line 1, remove abstract
- BAt line 9, insert super();
- CAt line 12, remove public
- DAt line 17, insert super (x);
- EAt line 17, insert super (); super.side = x;
- FAt line 20, use public void area () {
How the community answered
(44 responses)- A5% (2)
- C2% (1)
- D84% (37)
- E9% (4)
Explanation
D is correct because Rectangle extends Square, and Square defines only a parameterized constructor Square(int side) - meaning Java does not auto-generate a no-arg constructor. Without an explicit super(x) call, Rectangle's constructor would try to invoke a non-existent Square(), causing a compile error. F is correct because Java prohibits narrowing a method's access modifier when overriding: Square.area() is public, so Rectangle.area() cannot silently drop to package-private (default) - it must be public or wider.
Why the distractors fail:
- A - Removing
abstractis unnecessary; an abstract class with a no-arg constructor is valid Java and isn't causing any error here. - B - Square's constructor already compiles without an explicit
super()becauseShapedoes have a no-arg constructor, so the compiler inserts the call automatically. - C - Removing
publicfromSquare.area()would create a new error: overridingShape'sprotectedmethod with package-private access is itself an illegal narrowing. - E -
super()would invokeSquare's no-arg constructor, which doesn't exist, so this fails to compile.
Memory tip: Think "two constructor rules": (1) if a parent has no default constructor, you must call super(args) explicitly; (2) when overriding, access can only go up (protected → public is fine; public → default is not). Both rules come from the hierarchy flowing downward.
Community Discussion
No community discussion yet for this question.