Multiple choice technology programming languages

Given: 10. class Nav{ 11. public enum Direction { NORTH, SOUTH, EAST, WEST } 12. } 13. public class Sprite{ 14. // insert code here 15. } Which code, inserted at line 14, allows the Sprite class to compile?14

  1. Direction d = NORTH;

  2. Nav.Direction d = NORTH;

  3. Direction d = Direction.NORTH;

  4. Nav.Direction d = Nav.Direction.NORTH;

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

The Direction enum is defined inside the Nav class, so it's a nested enum. To access its constants, you must qualify it with the outer class name first: Nav.Direction. Then to access the NORTH constant, you use Nav.Direction.NORTH. Options A and B fail because Direction alone is not in scope. Option C is incorrect because Direction.NORTH tries to use Direction as a standalone type, but it's nested inside Nav.

AI explanation

To answer this question, you need to understand how to access an enum type that is defined inside a class.

In the given code, the enum Direction is defined inside the class Nav. The Sprite class is trying to access this enum.

Let's go through each option to understand why it is correct or incorrect:

Option A) Direction d = NORTH; - This option is incorrect because NORTH is not directly accessible in the Sprite class. To access the NORTH value, you need to specify the enum type Direction.

Option B) Nav.Direction d = NORTH; - This option is incorrect because NORTH is not directly accessible in the Sprite class. Additionally, the correct way to access the enum type Direction is by using Nav.Direction to specify the fully qualified name.

Option C) Direction d = Direction.NORTH; - This option is incorrect because Direction.NORTH is not directly accessible in the Sprite class. To access the NORTH value, you need to specify the enum type Direction.

Option D) Nav.Direction d = Nav.Direction.NORTH; - This option is correct because it specifies the fully qualified name Nav.Direction to access the enum type Direction and the NORTH value. This allows the Sprite class to compile successfully.

The correct answer is option D. This option is correct because it correctly accesses the enum type Direction using the fully qualified name Nav.Direction and initializes the variable d with the value Nav.Direction.NORTH.