Bird
0
0

Given the following classes, which statement is true about accessing the score field?

hard🚀 Application Q8 of 15
C Sharp (C#) - Inheritance

Given the following classes, which statement is true about accessing the score field?

public class Game {
    protected int score = 0;
}

public class Player : Game {
    public void IncreaseScore() {
        score += 10;
    }
}

public class Spectator {
    public void ShowScore() {
        Game g = new Game();
        // Can we access g.score here?
    }
}
ASpectator can access g.score because it is public by default.
BSpectator can access g.score because it is in the same assembly.
CSpectator cannot access g.score because it is protected and Spectator is not derived from Game.
DSpectator can access g.score only if it creates a Player instance.
Step-by-Step Solution
Solution:
  1. Step 1: Identify access modifier and class relationships

    Score is protected in Game; Spectator is unrelated to Game.
  2. Step 2: Apply protected access rules

    Protected members accessible only in class and derived classes, not unrelated classes.
  3. Final Answer:

    Spectator cannot access g.score because it is protected and Spectator is not derived from Game. -> Option C
  4. Quick Check:

    Protected members inaccessible to unrelated classes [OK]
Quick Trick: Protected members hidden from unrelated classes even in same assembly [OK]
Common Mistakes:
MISTAKES
  • Assuming protected means public
  • Confusing assembly scope with protected scope
  • Thinking creating derived instance grants access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes