Definition: Inheritance allows a class (derived class) to acquire properties and behaviors (methods) from another class (base class).
Base Class: The class that provides the inherited members.
Derived Class: The class that inherits from the base class.
Syntax:
csharp
Copy code
class DerivedClass : BaseClass
{
// Additional methods and fields
}
2. Accessing Base Class Members
Inherited Members: A derived class has access to public and protected members of its base class.
Example:
csharp
Copy code
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}
class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking..."); }
}
// Usage
Dog dog = new Dog();
dog.Eat(); // Inherited from Animal
dog.Bark(); // Specific to Dog
3. Virtual Methods and Overriding
Virtual Method: A method in the base class that can be overridden in the derived class.
Use the virtual keyword in the base class and override in the derived class.
Syntax:
csharp
Copy code
class Animal
{
public virtual void Speak() { Console.WriteLine("Animal Sound"); }
}
class Dog : Animal
{
public override void Speak() { Console.WriteLine("Woof"); }
}
Calling Base Implementation: Use base.MethodName() in the derived class to call the base class’s implementation.
4. Abstract Classes
Abstract Class: Cannot be instantiated and may contain abstract methods (methods without implementation).
Abstract Method: Must be implemented in any derived non-abstract class.
Syntax:
csharp
Copy code
abstract class Animal
{
public abstract void Speak();
}
class Dog : Animal
{
public override void Speak() { Console.WriteLine("Woof"); }
}
5. The Object Class
All Classes Inherit from Object: This base class provides common methods such as ToString(), Equals(), and GetHashCode(), which can be overridden for custom behavior.
6. Polymorphism Through Inheritance
Polymorphism: The ability of different derived classes to be treated as instances of their base class, each implementing its version of a method.
Example:
csharp
Copy code
Animal myAnimal = new Dog(); // Base type reference, derived type object
myAnimal.Speak(); // Calls Dog’s implementation of Speak()
7. Inheritance Hierarchies and Class Diagrams
Inheritance Hierarchies: Shows the structure of how classes relate in inheritance, with base classes at the top.
UML Class Diagrams:
Arrow Notation: A solid line with a hollow triangle pointing to the base class represents inheritance in UML diagrams.
Quick Study Tips for MCQs
Distinguish Access Levels: Know how public, protected, and private affect inheritance.
Virtual and Override Keywords: Understand when to use these for polymorphic behavior.
Abstract Classes: Recognize that abstract methods require implementation in derived classes.
Object Class Methods: Remember key methods (ToString(), Equals()) that can be overridden.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (