Java OCA OCP Practice Question 1547

Question

Let's say Shape is a class that contains a public member inner class called Rectangle.

Given that shape is an instance of Shape,

how would you instantiate a new Rectangle from within a static method, such as main()?

  • A. new Rectangle();
  • B. shape.Rectangle();
  • C. Shape.new Rectangle();
  • D. shape.new Rectangle();


D.

Note

Member inner classes require an instance of the surrounding class to be instantiated.

Option A is incorrect since we are told that the instantiation request is from a static method.

Note that this call would be valid from a non-static method in Shape.

Option B is incorrect because it lacks the new keyword.

Option C is incorrect.

Rectangle is a member inner class, not a static nested class.

Option D is correct and uses the instance shape to create a new Rectangle object.




PreviousNext

Related