Inheritance
Inheritance
Inheritance
// Base class
1. Base Class (Parent Class): This is the class whose members are inherited. It defines the
common characteristics and behaviors that its derived classes will share.
2. Derived Class (Child Class): This is the class that inherits from the base class. It can add
new members (fields and methods), override the inherited members to provide a
specialized implementation, or simply use the inherited members as they are.
3. : Syntax for Inheritance: In C#, you use a colon (:) followed by the name of the base
class when declaring a derived class.
C#
using System;
namespace ShapeApp
{ public class Shape
{
public string Color;
public Shape(string assign_color)
{ Color = assign_color; }
using System;
namespace ShapeApp
{
public class Circle : Shape
{
public double Radius;
public Circle(string assign_color, double radius)
{
Radius = radius;
}
public override double Area()
{
return Math.PI * Math.Pow(Radius, 2);
}
public override string Display()
{
return base.Display() + $", Shape: Circle, Radius:
{Radius}, Area: {Area():F2}";
}
}
}
Now here:
1. Inheritance allows code reuse: A derived class can inherit properties, methods, and behavior
from a base class.
2. Base class and derived class: The base class is the parent class, and the derived class is the
child class that inherits from the base class.
3. Single inheritance: C# supports single inheritance, where a derived class can inherit from
only one base class.
4. Multilevel inheritance: A derived class can inherit from a base class that itself inherits from
another base class. e.g.
class A{ } class B:A { } class C:B { }
here class C inherits from class B and class A (through B).
5. Access modifiers: Access modifiers (public, protected, internal, private) control access to
members of a class.
6. Virtual and override: Virtual methods in the base class can be overridden in the derived class
using the override keyword.
7. Sealed classes and methods: Sealed classes cannot be inherited from, and sealed methods
cannot be overridden.
8. Abstract classes and methods: Abstract classes cannot be instantiated and are intended to be
inherited from. Abstract methods are declared without implementation and must be
implemented in derived classes.
2. Access Modifiers and Inheritance
When inheriting, members of the base class are accessible based on their access modifiers:
* An assembly is an executable (.exe) or dynamic link library (.dll) produced from compiling
source code.
Sealed Keyword:
The sealed keyword in C# is used to restrict inheritance or overriding.
Sealed Class: A sealed class cannot be inherited from. It cannot be used as base class.
public sealed class Rectangle
{
// class members
}
Sealed Method: A sealed method cannot be overridden in derived classes. Unlike private which
is not inherited, sealed is inherited in derived class but it cannot be overridden.
class BaseClass
{
public virtual void MyMethod() {
Console.WriteLine("Base Method"); }
}