Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard

Question 30

Below is the code to Test.java file:

What will be the result of compiling and executing Test class?

  • A Compilation error
  • B Drawing a RECTANGLE
  • C Drawing a CIRCLE
  • D Drawing a SQUARE
Reveal correct answer

Correct answer: A

Explanation

At the time of creating the instance of anonymous inner class, new Shape() is used, which means it is looking for a no-argument constructor in anonymous inner class code, which would invoke the no-argument constructor of super class, Shape.

But as parameterized constructor is specified in Shape class, so no-argument constructor is not provided by the compiler and hence compilation error.


To correct the compilation error, pass the enum constant while instantiating anonymous inner class. 

Shape shape = new Shape(ShapeType.CIRCLE) {...}; or you can even pass null: Shape shape = new Shape(null) {...};  OR provide the no-argument constructor in the Shape class: Shape(){}

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need