0% found this document useful (0 votes)
19 views11 pages

C# Inheritance and Polymorphism Guide

This document covers the concepts of inheritance and polymorphism in C#, detailing the types of inheritance such as single, multilevel, hierarchical, and the limitations regarding multiple inheritance. It explains how derived classes inherit properties from base classes and the rules governing access to members, constructors, and destructors. Additionally, it provides code examples to illustrate single level and multilevel inheritance, as well as the use of constructors in derived classes.

Uploaded by

newtoyou.p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views11 pages

C# Inheritance and Polymorphism Guide

This document covers the concepts of inheritance and polymorphism in C#, detailing the types of inheritance such as single, multilevel, hierarchical, and the limitations regarding multiple inheritance. It explains how derived classes inherit properties from base classes and the rules governing access to members, constructors, and destructors. Additionally, it provides code examples to illustrate single level and multilevel inheritance, as well as the use of constructors in derived classes.

Uploaded by

newtoyou.p
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BCA easy C# Concept Tutorials UNIT-III

Inheritance and Polymorphism

 Inheritance
C# is pure object-oriented language.
C# has the ability to create new classes from the existing classes.
Reusability is achieved by designing new classes, reusing all or some of the
properties of existing ones.
When we want to add more properties to an existing class without
actually modifying it, we use inheritance and for that we define derived class.

Mechanism of designing or constructing a class from another class is called


inheritance.

A class that is inherited is called base class. ( or superclass or parent class).


The class that does the inheriting is called derived class ( or subclass or child
class).
Derived class is specified version of base class. Derived class inherits all of
the members defined by the base class and add its own unique elements.

( Existing class from which new class is derived is called base class.
Newly derived class from existing class is called derived class. )

Inheritance may be achieved in two different forms:


• Classical form
• Containment form

Classical inheritance may be implemented in different combinations such as:


single inheritance, multiple inheritance( C# does not provide this type),
Hierarchical inheritance, multilevel inheritance.

C# does not directly implement multiple inheritance.


Multiple inheritance can be implemented using concept of interface.

Concept Tutorial – 9823471684 I-1


BCA easy C# Concept Tutorials UNIT-III

Types of Inheritance:
1) Single inheritance or Single level inheritance:
When class derived from single base class such type of inheritance is
called single level inheritance.

2) Multilevel inheritance: IMP ***


When class derived from another derived class such type of inheritance is
called multilevel inheritance.

3) Hierarchical inheritance:
When multiple (i.e. two or more) classes derived from same base class
such type of inheritance is called hierarchical inheritance.

4) Multiple inheritance:
When class derived from more than one base classes such type of
inheritance called multiple inheritance.
C# does not directly implement multiple inheritance.
Multiple inheritance can be implemented using concept of interface.

Figure: types of Inheritance

Characteristics of inheritance are:


1. A derived class extends its direct base class. It can add new members to those
it inherits. It cannot change or remove the definition of an inherited member.

Concept Tutorial – 9823471684 I-2


BCA easy C# Concept Tutorials UNIT-III

2. Constructors and destructors are not inherited. All other members are
inherited. Their accessibility in the derived class depends on their declared
accessibility in the base class.
3. An instance of a derived class contains a copy of all instance fields (i.e. data
members) declared in the class and its base classes.
4. A derived class can hide an inherited member.
5. A derived class can override an inherited member.
========================================================

Defining a subclass (or derived class): VIMP ***


General form for defining a subclass:
class subclassname : baseclassname
{
variables declaration;
-----
methods declaration;
------
}
Here,
class - is keyword used to define class
subclassname - name of subclass
baseclassname - name of baseclass
subclassname and baseclassname are valid C# identifiers.
colon ( : ) signifies that properties of baseclass are extended to subclassname.

When implemented the subclass will contain its own members as well those of
the baseclass.

You can specify only one base class for any derived class that you create.
C# does not support the inheritance of multiple base classes into a single derived
class.
Derived class inherits (or includes) all of the members of base class.
A private member of a base class is not accessible to a derived class.
Derived class cannot access private members of the base class.

Concept Tutorial – 9823471684 I-3


BCA easy C# Concept Tutorials UNIT-III

A protected member is created by using the protected access modifier.


When member are declared as protected then such a member are accessible
in all derived classes.

When a derived class is used as a base class for another derived class, any
protected member of the initial base class that is inherited by the first derived
class is also inherited as protected by a second derived class.

/* Program to explain single level inheritance */


/* program to explain superclass (base class) and subclass */

using System;
class Data
{
protected int a;
public void Setdata(int x)
{
a = x;
}
public void Showdata()
{ [Link]("a=" + a);
}
}
class SData : Data
{
public void Square()
{ int s = a * a;
[Link]("square=" + s);
}
}
class Test
{
public static void Main( )

Concept Tutorial – 9823471684 I-4


BCA easy C# Concept Tutorials UNIT-III

{
SData s1 = new SData( );
[Link](4);
[Link]( );
[Link]();
}
}
Output:
a=4
square=16
===========================================================

Multilevel Inheritance or Multilevel hierarchy: VIMP***


When class derived from another derived class such type of inheritance is
called multilevel inheritance.

The class A serves as a base class for the derived class B which in turn
serves as a base class for the derived class C. The chain ABC is known as
inheritance path.

Derived class with multilevel base classes is declared as follows:


class A
{
-----
}
class B : A // first level derivation

Concept Tutorial – 9823471684 I-5


BCA easy C# Concept Tutorials UNIT-III

{
-----
}
class C : B // second level derivation
{
-----
}

The class C can inherit the members of both A and B.

The constructors are executed from top downwards, with the bottom
most class constructor being executed last.
In a class hierarchy, the constructors are called in order of derivation,
from base class to derived class.
That is, the constructors are executed in order of derivation.

/* Program to explain Multilevel inheritance */


using System;
class Data
{
protected int a;
public void Setdata(int x)
{ a = x;
}
public void Showdata()

Concept Tutorial – 9823471684 I-6


BCA easy C# Concept Tutorials UNIT-III

{ [Link]("a=" + a);
}
}
class SData : Data
{
public void Square()
{ int s = a * a;
[Link]("square=" + s);
}
}
class CData : SData
{
public void Cube()
{ int c = a * a * a;
[Link]("cube=" + c);
}
}
class Test
{
public static void Main()
{
CData c1 = new CData();
[Link](4);
[Link]();
[Link]();
[Link]();
}
}
Output:
a=4
square=16
cube=64

Concept Tutorial – 9823471684 I-7


BCA easy C# Concept Tutorials UNIT-III

Hierarchical Inheritance:
When multiple (i.e. two or more) classes derived from same base class
such type of inheritance is called hierarchical inheritance.
Inheritance is used for hierarchical classification.

/* Program to explain hierarchical inheritance */


using System;
class Data
{
protected int a;
public void Setdata(int x)
{ a = x;
}
public void Showdata()
{ [Link]("a=" + a);
}
}
class SData : Data
{
public void Square()
{ int s = a * a;
[Link]("square=" + s);
}
}
class CData : Data

Concept Tutorial – 9823471684 I-8


BCA easy C# Concept Tutorials UNIT-III

{
public void Cube()
{ int c = a * a * a;
[Link]("cube=" + c);
}
}
class ITest
{
public static void Main()
{
SData s1 = new SData();
[Link](4);
[Link]();
[Link]();
[Link]("----------------");
CData c1 = new CData();
[Link](4);
[Link]();
[Link]();
}
}

Output:
a=4
square=16
----------------
a=4
cube=64
=======================================

Concept Tutorial – 9823471684 I-9


BCA easy C# Concept Tutorials UNIT-III

Constructor and Inheritance:


Calling base class constructor
A derived class can call a constructor defined in its base class by using an
explanded form of derived class constructor declaration and its base keyword.
General form is:
derivedconstructor(parameter-list) : base (arg-list)
{
// body of constructor
}
Here, arg-list specifies any arguments needed by constructor in the base class.

Any form of constructor defined by the base class can be called by base.
The constructor executed will be the one that matches the arguments.
When a derived class specifies a base clause, it is calling the constructor
of its immediate base class. The base always refers to a base class immediately
above the calling class. If no base clause is present, then the base class default
constructor is called automatically.

/* Program to explain constructor and inheritance */


using System;
class Data
{
protected int a;
public Data(int x)
{ a = x;
[Link]("inside base class constructor");
}
public void Showdata()
{ [Link]("a=" + a);
}
}
class SData : Data
{

Concept Tutorial – 9823471684 I-10


BCA easy C# Concept Tutorials UNIT-III

public SData(int x): base(x)


{ [Link]("inside derived class constructor");
}
}
class Test
{
public static void Main()
{
SData s1 = new SData(4);
[Link]();
}
}
Output:
inside base class constructor
inside derived class constructor
a=4

Base always refers to the constructor in the closest base class. In a class
hierarchy, if a base class constructor requires parameters, then all derived
classes must pass those parameters “up the line”. This is true whether or not a
derived class needs parameters of its own.
In a class hierarchy, the constructors are called in order of derivation, from
base class to derived class.
That is, the constructors are executed in order of derivation.
If base is not used, then the default (parameterless) constructor of each base
class will be executed.

======================================

Concept Tutorial – 9823471684 I-11

Common questions

Powered by AI

Reusability in inheritance is integrated by allowing derived classes to inherit and utilize the functionality of base classes without rewriting code. In C#, this is facilitated through class mechanisms where derived classes can extend, override, or hide members of base classes to modify behavior as needed. C# enforces encapsulation through access modifiers, ensuring only necessary members are exposed, which promotes code reuse while maintaining object-oriented principles. Interfaces further enhance reusability by allowing different classes to implement common operations, fostering flexible code structures .

Inheritance as a design mechanism can lead to challenges such as tight coupling between base and derived classes, which might hinder reusability since changes in the base class affect all derived classes. Additionally, deep inheritance hierarchies can complicate class maintenance due to difficulty in tracking method overrides and interdependencies. This can lead to fragile designs where unintended alterations propagate through subclasses, requiring careful planning and use of design patterns like composition over inheritance to mitigate these issues .

A derived class may override a member from its base class to provide a specialized or more context-specific implementation, tailoring general functionality to fit particular needs of the subclass. This impacts class behavior by changing the way overridden members interact with other class members, ensuring derived classes can modify or enhance base class functionality without altering the base class itself. Overriding supports polymorphic behavior in class hierarchies, where methods are dynamically selected based on object types .

Hierarchical classification in C# is the process of organizing classes into a structure where multiple derived classes inherit from a common base class. This reflects hierarchical inheritance, where derived classes are specialized versions that build on the common functionality provided by the base class. Hierarchical classification helps structure programs through clear inheritance paths, promoting reuse and clarity by categorizing classes based on shared characteristics and varied specializations .

C# does not support multiple inheritance directly due to complexity and ambiguity issues that arise, such as diamond problem. Instead, C# utilizes interfaces, which allow a class to implement multiple sets of functionalities defined in various interfaces. This approach provides a controlled way of achieving the benefits of multiple inheritance while avoiding its pitfalls, allowing classes to adhere to several contracts and behaviors without complex inheritance trees .

In a multilevel inheritance hierarchy in C#, constructors are executed from the base class up to the derived class. For instance, when a class A serves as a base for class B, and class B serves as a base for class C, the constructor chain executed during object creation starts at class A, then class B, and finally class C. If base class constructors require parameters, they must be passed through all levels of derivation, ensuring proper initialization .

In hierarchical inheritance, multiple derived classes inherit from a single base class, sharing its members while also adding their own. Practically, this allows creating a class that provides common functionality which other specialized classes use. For example, a base class might handle basic data manipulation while derived classes perform specific operations like calculating squares or cubes of data, sharing common methods and properties .

In C#, the protected access modifier allows class members to be accessible within its own class and by derived classes, unlike private which restricts access solely to its own class, and public which exposes members to all classes. This ensures encapsulation while enabling derived classes to utilize and extend base functionality. Protected members are particularly useful in inheritance hierarchies where derived classes need to build on existing base class behaviors .

The base keyword is used in derived class constructors to explicitly call a specific constructor of a base class and pass necessary parameters. This is essential when base class constructors require parameters because it ensures that the base class is properly initialized with the given values. Without using base, the default constructor would be called, which may not be desirable or even available if the base class defines only parameterized constructors .

Inheritance in C# can be achieved through two primary mechanisms: classical inheritance and containment form. Classical inheritance includes single, multilevel, and hierarchical inheritances, but C# does not support multiple inheritance due to potential ambiguities. Instead, multiple inheritance is emulated through interfaces. Classical inheritance allows derived classes to extend base classes by adding new members, while containment involves a class containing instances of other classes as members to mimic inheritance-like relationships .

You might also like