Bird
0
0

Consider this code:

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

Consider this code:

class Animal {
    protected string name = "Unknown";
}

class Dog : Animal {
    public string GetName() {
        return name;
    }
}

class Cat {
    public string GetAnimalName() {
        Animal a = new Animal();
        return a.name;
    }
}

Which statement is correct?

ACat can access 'name' but Dog cannot.
BBoth Dog and Cat can access 'name' because it is protected.
CNeither Dog nor Cat can access 'name' because it is private.
DDog can access 'name' but Cat cannot access 'name' from Animal instance.
Step-by-Step Solution
Solution:
  1. Step 1: Check access in derived class Dog

    Dog inherits Animal and can access protected 'name' directly.
  2. Step 2: Check access in unrelated class Cat

    Cat tries to access protected 'name' via Animal instance, which is not allowed.
  3. Final Answer:

    Dog can access 'name' but Cat cannot access 'name' from Animal instance. -> Option D
  4. Quick Check:

    Protected access allowed in subclass, denied in unrelated class [OK]
Quick Trick: Protected members accessible only in subclass, not unrelated classes [OK]
Common Mistakes:
MISTAKES
  • Assuming protected means accessible everywhere
  • Confusing private and protected
  • Accessing protected members via instance in unrelated class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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