Lecture 07 C Inheritance and Polymorphism Dr Eng





























![Abstract Classes Cannot Instantiated abstract class Vehicle { } static void Main(string[] args) { Abstract Classes Cannot Instantiated abstract class Vehicle { } static void Main(string[] args) {](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-30.jpg)























![Declaring and Implementing a Delegate: [access modifier] delegate Result_type Identifier([parameters]); Example: 1 - public Declaring and Implementing a Delegate: [access modifier] delegate Result_type Identifier([parameters]); Example: 1 - public](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-54.jpg)


![class Program { Static void Main(string[ ] args) { int x=4, y=5; Class 1 class Program { Static void Main(string[ ] args) { int x=4, y=5; Class 1](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-57.jpg)

- Slides: 58

Lecture 07 C# - Inheritance and Polymorphism Dr. Eng. Ibrahim El-Nahry

Learning Objectives n n n n n Inheritance Implementing Inheritance in C# Constructor calls in Inheritance Protected Access Modifier The Sealed Keyword Object Class Polymorphism Overriding Methods Keywords 2

Inheritance n n Inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined. The new classes, known as derived classes, take over (or inherit) attributes and behavior of the pre-existing classes Objects of derived class are objects of base class but not vice versa A derived class can only access non-private base class members n Unless it inherits accessor functions that allow for such access 3

Contd… n The existing class is called the parent class, or superclass, or base class n The derived class is called the child class, or subclass, or derived class. n As the name implies, the child inherits characteristics of the parent n That is, the child class inherits the methods and data defined for the parent class 4

Inheritance - Examples 5

Single and Multiple inheritances n n Single inheritance: deriving from one base class Multiple inheritance: deriving from two or more base classes 6

Implementing Inheritance in C# C# uses the colon ': ' operator to indicate inheritance. Sample code 7

Controlling Inheritance n n Visibility modifiers determine which class members get inherited and which do not Variables and methods declared with public visibility are inherited, and those with private visibility are not But public variables violate our goal of encapsulation There is a third visibility modifier that helps in inheritance situations: protected n can be accessed by base class or any class derived from that base class 8

“base” keyword n The base keyword is used to access members of the base class from within a derived class: n n Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance method, or an instance property accessors. It is an error to use the base keyword from within a static method. 9

Constructor calls in Inheritance When we instantiate the sub-class, the compiler first instantiates the bas -class by calling one of its constructors and then calling the constructor of the sub-class. 10

Calling Constructors of Base Class We can explicitly call the constructor of a base-class using the keyword base must be used with the constructor header (or signature or declaration) after a colon ': ' operator 11 11

12

13

Types Protected Access Modifier Ø Ø Ø C# provides the protected access modifier to protect the data. Protected members of the class can be accessed either inside the containing class or inside its sub-class. Users still won't be able to call the protected members through object references and if one tries to do so, the compiler will generate an error. 14

Protected Internal Access Modifier In a similar way, the protected internal access modifier allows a member (field, property and method) to be accessed: Ø Inside the containing class, or Ø Inside the same project, or Ø Inside the sub-class of the containing class. Ø Hence, protected internal acts like 'protected OR internal', i. e. , either protected or internal. 15

internal class Base. Class { public static int Int. M = 0; } class Test. Access { public static void Main() { Base. Class my. Base = new Base. Class(); // error, Base. Class not visible outside assembly } } 16

Important Point 17

Object Class Ø Ø Ø In C# all the types (classes, structures and interfaces) are implicitly inherited from the Object class defined in the System namespace. This class provides the lowlevel services and general methods to each and every class in the. NET framework. The Object class is extremely useful when it comes to polymorphism, as a reference of type Object can hold any type of object. Object Class Methods Ø Ø Ø Ø Equals Static Equals Get. Hash. Code Get. Type Static Reference. Equals To. String Protected. Finalize Protected. Memberwise. Clone 18

Polymorphism Ø Ø Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides. 19

The new keyword Ø C# introduces a keyword new to mark a method as a nonoverriding method and as the one which we don't want to use polymorphically. 20

The new keyword n n n n n n n class BC { public void Display() { System. Console. Write. Line("BC: : Display"); } } class DC : BC { new public void Display() { System. Console. Write. Line("DC: : Display"); } } class Demo { public static void Main() { BC b; b = new BC(); b. Display(); } } Output BC: : Display 21

n n n n n n n class BC { public void Display() { System. Console. Write. Line("BC: : Display"); } } class DC : BC { new public void Display() { System. Console. Write. Line("DC: : Display"); } } class Demo { public static void Main() { BC b; b = new BC(); b. Display(); b = new DC(); b. Display(); } } Output BC: : Display 22

n n n n n n n n n n class BC { public void Display() { System. Console. Write. Line("BC: : Display"); } } class DC : BC { new public void Display() { System. Console. Write. Line("DC: : Display"); } } class TC : BC { new public void Display() { System. Console. Write. Line("DC: : Display"); } } class Demo { public static void Main() { BC b; b = new BC(); b. Display(); b = new DC(); b. Display(); b = new TC(); b. Display(); } } Output BC: : Display 23

Method Overriding Ø Ø Virtual and Override keywords Sample code allows you to implement Methods Overriding in Base and Derived Classes. Different implementations of a method with the same name and signature in the base and subclasses is called as Polymorphism. override keyword is needed if a derived-class method overrides a base-class method If a base class method is going to be overridden it must be declared virtual 24

Method Overriding n n n n n n n class BC { public virtual void Display() { System. Console. Write. Line("BC: : Display"); } } class DC : BC { public override void Display() { System. Console. Write. Line("DC: : Display"); } } class Demo { public static void Main() { BC b; b = new BC(); b. Display(); b = new DC(); b. Display(); } } Output BC: : Display DC: : Display 25

n n n n n n n n class BC { public virtual void Display() { System. Console. Write. Line("BC: : Display"); } } class DC : BC { public override void Display() { System. Console. Write. Line("DC: : Display"); } } class TC : DC { public new void Display() { System. Console. Write. Line("TC: : Display"); } } class Demo { public static void Main() { BC b; b = new TC(); b. Display(); } } Output DC: : Display 26

Abstraction n n In object-oriented programming, abstraction is one of three central principles (along with encapsulation and inheritance) Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency 27

Abstraction n Abstract classes n n Cannot be instantiated Used as base classes Class definitions are not complete – derived classes must define the missing pieces Can contain abstract methods and/or abstract properties n Have no implementation n Derived classes must override inherited abstract methods and properties to enable instantiation 28

Abstract base classes In C#, the abstract modifier is used to declare an abstract class 29
![Abstract Classes Cannot Instantiated abstract class Vehicle static void Mainstring args Abstract Classes Cannot Instantiated abstract class Vehicle { } static void Main(string[] args) {](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-30.jpg)
Abstract Classes Cannot Instantiated abstract class Vehicle { } static void Main(string[] args) { // Abstract Class cannot be instantiated Vehicle obj = new Vehicle(); // Shows Compilation Error. } 30

Abstract Methods abstract class Vehicle { public abstract void Run(); } class Car : Vehicle { public override void Run() { Console. Write. Line("Run the Car"); } } class Bus : Vehicle { public override void Run() { Console. Write. Line("Run the Bus"); } } Abstract methods contain the function signature and return type, but no body. A child class can override the abstract method thus providing its implementation. Abstract methods are also declared by using the abstract keyword. A method must be declared as abstract or virtual to be overridden inside the child class. Note: Abstract methods can only be defined inside an abstract class. 31

Why must make everything abstract? n n The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs 32

Interfaces n n n An interface is a collection of method definitions (without implementations) and constant values. An interface is like a pure abstract base class Notes: n A class that implements a particular interface must implement the members listed by that interface 33

Differences between Abstract Classes Vs. Interfaces n The biggest difference between an abstract class and an interface is: A class may implement an unlimited number of interfaces, but may inherit from only one abstract 34

Declaring Interfaces They are declared similar to how classes are. Only differences are that they can only contain methods and properties (no variables), they do not contain the definition for these methods/properties and off-course the interface keyword. Example (1) class Demo { public static void Main() { System. Console. Write. Line("Hello Interfaces"); } } interface abc { void xyz(); } Output Hello Interfaces Example (2) class Demo { public static void Main() { System. Console. Write. Line("Hello Interfaces"); } } interface abc { } Output Hello Interfaces 35

Example 3 class Demo { public static void Main() { System. Console. Write. Line("Hello Interfaces"); } } interface abc { int x; } Output error Interfaces cannot contain fields 36

Example 4 { public static void Main() { System. Console. Write. Line("Hello Interfaces"); } } interface abc { void xyz() { System. Console. Write. Line("In xyz"); } } Output error : 'abc. xyz()': interface members cannot have a definition 37

Example 5 class Demo : abc { public static void Main() { System. Console. Write. Line("Hello Interfaces"); xyz(); } public void xyz() { System. Console. Write. Line("In xyz"); } } interface abc { void xyz(); } Output Hello Interfaces In xyz 38

Example 6 class Demo : abc { public static void Main() { System. Console. Write. Line("Hello Interfaces"); Demo ref. Demo = new Demo(); ref. Demo. xyz(); Sample ref. Sample = new Sample(); ref. Sample. xyz(); } public void xyz() { System. Console. Write. Line("In Demo : : xyz"); } } interface abc { void xyz(); } class Sample : abc { public void xyz() { System. Console. Write. Line("In Sample : : xyz"); } } Output In Demo : : xyz In Sample : : xyz 39

Multiple Inheritance n n C# does not support multiple inheritance? Multiple inheritance tends to cause more problems than it solves. However, the ability to derive methods and properties from multiple sources is present in C#. This is done using Interfaces only contain the declaration part of a class. The actual definition which comprises of the body of the method is present inside the class which implements the interface. Multiple interfaces can be used using comma(, ). Thus allowing multiple inheritance, by implementing more than interface. 40

Implementing Multiple Interfaces 41

A Class cannot have multiple Base Classes 42

The sealed keyword Finally, if you don't want your class to be inherited by any class, you can mark it with the sealed keyword. No class can inherit from a sealed class. Sample Code 43

A file can declare multiple namespaces. 44

Namespaces n Namespace CS 415 n Class A n Class B n Class C n Method of grouping elements (such as classes and other namespaces) to avoid naming collisions Allow hierarchical organization of classes Permits isolation of names Can be nested Access via fully qualified names Namespace CS 340 Class A Class B CS 415. A… CS 340. A… Class C 45

Why Namespaces? ? n n n Namespaces are meant for HUGE programs and frameworks In a huge program with different modules designed by different companies there may be classes with the same name If each company uses their company name as their namespace, naming collisions are reduced substantially (full names of classes, not only their own name). 46

n n n n n n namespace Flat. Shapes { class Circle { private double _radius; public double Radius { get { return (_radius < 0) ? 0. 00 : _radius; } set { _radius = value; } } public double Diameter { get { return Radius * 2; } } public double Circumference { get { return Diameter * 3. 14159; } } public double Area { get { return Radius * 3. 14159; } } 47

n n n n namespace Volumes { class Sphere : Flat. Shapes. Circle { new public double Area { get { return 4 * Radius * 3. 14159; } } public double Volume { get { return 4 * 3. 14159 * Radius / 3; } } 48

n n n n n n using System; using Volumes; using Flat. Shapes; class Exercise { static void Show(Circle round) { Console. Write. Line("Circle Characteristics"); Console. Write. Line("Side: {0}", round. Radius); Console. Write. Line("Diameter: {0}", round. Diameter); Console. Write. Line("Circumference: {0}", round. Circumference); Console. Write. Line("Area: {0}", round. Area); } static void Show(Sphere ball) { Console. Write. Line("n. Sphere Characteristics"); Console. Write. Line("Side: {0}", ball. Radius); Console. Write. Line("Diameter: {0}", ball. Diameter); Console. Write. Line("Circumference: {0}", ball. Circumference); Console. Write. Line("Area: {0}", ball. Area); Console. Write. Line("Volume: {0}n", ball. Volume); } 49

public static int Main() { Flat. Shapes. Circle c = new Flat. Shapes. Circle(); Volumes. Sphere s = new Volumes. Sphere(); c. Radius = 20. 25; Show(c); s. Radius = 20. 25; Show(s); return 0; } n n n } This would produce: Circle Characteristics Side: 25. 55 Diameter: 51. 1 Circumference: 160. 535249 Area: 2050. 837805975 Sphere Characteristics Side: 25. 55 Diameter: 51. 1 Circumference: 160. 535249 Area: 8203. 3512239 Volume: 69865. 2079235483 50

Indexers n n n Indexers allow you to index a class instance in the same way as an array An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ] Next slide show: Indexer example 51

52

Delegates n n n A delegate is a C# language element that allows you to reference a method. Delegates must be declared before use A delegate declaration specifies the parameters and return type of the methods The delegate can refer to Methods who can be referred to by a delegate, must have the same signature as the delegate Delegate instances can then be created to refer to a method(s) Once a delegate instance is created, the method it refers to can be invoked 53
![Declaring and Implementing a Delegate access modifier delegate Resulttype Identifierparameters Example 1 public Declaring and Implementing a Delegate: [access modifier] delegate Result_type Identifier([parameters]); Example: 1 - public](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-54.jpg)
Declaring and Implementing a Delegate: [access modifier] delegate Result_type Identifier([parameters]); Example: 1 - public delegate int mon_delegate ( int val 1, int val 2); 2 - mon_delegate del_max= new mon_delegate(max); 3 - public int max(int x, int y) { if(x<y) return x; else return y; } 4 - m= del_max(10, 12); 54

using system; class Class 1 { public delegate int mon_delegate ( int val 1, int val 2); public Class 1(int choice, int x, int y) { Switch(choice) { case 1: mon_delegate del_max= new mon_delegate(max); int ma = del_max(x, y); Console. Write. Line(“The Value max is : ”+ ma); break; case 2: mon_delegate del_min= new mon_delegate(min); int mi = del_min(x, y); Console. Write. Line(“The Value min is : ”+ mi); break; case 3: mon_delegate del_sum= new mon_delegate(sum); int s = del_sum(x, y); Console. Write. Line(“The sum is : ”+ s); break; 55

case 4: mon_delegate del_mul= new mon_delegate(mul); int mu = del_mul(x, y); Console. Write. Line(“The multip. is : ”+ mu); break; } } public int max(int x, int y) { if(x>y) return x; else return y; } public int min(int x, int y) { if(x<y) return x; else return y; } public int sum(int x, int y) { return (x+ y); } public int mul(int x, int y) { return (x* y); } } 56
![class Program Static void Mainstring args int x4 y5 Class 1 class Program { Static void Main(string[ ] args) { int x=4, y=5; Class 1](https://slidetodoc.com/presentation_image/036016103dec941d281e9f90a2ae1146/image-57.jpg)
class Program { Static void Main(string[ ] args) { int x=4, y=5; Class 1 c 1=new Class 1(1, x, y); Class 1 c 2=new Class 1(2, x, y); Class 1 c 3=new Class 1(3, x, y); Class 1 c 4=new Class 1(4, x, y); Console. Read. Key(); } } The program output: The value max is : 5 The value min is : 4 The sum is : 9 The multip. is : 20 57

Summary n n n n Inheritance allows a software developer to derive a new class from an existing one Derived class objects inherit members of base class n And may add members Private member variables in base class cannot be accessed "by name" in derived Private member functions are not inherited Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides. Delegates provide dynamic run-time method invocation services 58