Download presentation
Presentation is loading. Please wait.
Published byFelicia Logan Modified over 7 years ago
1
Lecture 07 C# - Inheritance and Polymorphism Dr. Eng. Ibrahim El-Nahry
2
Learning Objectives Inheritance Implementing Inheritance in C#
Constructor calls in Inheritance Protected Access Modifier The Sealed Keyword Object Class Polymorphism Overriding Methods Keywords
3
Inheritance 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 Unless it inherits accessor functions that allow for such access
4
Contd… The existing class is called the parent class, or superclass, or base class The derived class is called the child class, or subclass, or derived class. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class
5
Inheritance - Examples
6
Single and Multiple inheritances
Single inheritance: deriving from one base class Multiple inheritance: deriving from two or more base classes
7
Implementing Inheritance in C#
C# uses the colon ':' operator to indicate inheritance. Sample code For complete details, please refer the following URL: 7
8
Controlling Inheritance
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 can be accessed by base class or any class derived from that base class
9
“base” keyword The base keyword is used to access members of the base class from within a derived class: 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.
10
Constructor calls in Inheritance
When we instantiate the sub-class, the compiler first instantiates the base-class by calling one of its constructors and then calling the constructor of the sub-class. For complete details, please refer the following URL: 10
11
Calling Constructors of Base Class
We can explicitly call the constructor of a base-class using the keyword base. base must be used with the constructor header (or signature or declaration) after a colon ':' operator For complete details, please refer the following URL: 11 11
14
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. For complete details, please refer the following URL: 14
15
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. For complete details, please refer the following URL: 15
16
internal class BaseClass { public static int IntM = 0; }
class TestAccess public static void Main() BaseClass myBase = new BaseClass(); // error, BaseClass not visible outside assembly
17
Important Point
18
Object Class Object Class Methods Equals Static Equals GetHashCode GetType Static ReferenceEquals ToString ProtectedFinalize ProtectedMemberwiseClone 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 low-level 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. For complete details, please refer the following URL: 18
19
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. For complete details, please refer the following URL: 19
20
The new keyword C# introduces a keyword new to mark a method as a non-overriding method and as the one which we don't want to use polymorphically. For complete details, please refer the following URL: 20
21
The new keyword class BC { public void Display()
System.Console.WriteLine("BC::Display"); } class DC : BC new public void Display() System.Console.WriteLine("DC::Display"); class Demo public static void Main() BC b; b = new BC(); b.Display(); Output BC::Display
22
class BC { public void Display() System.Console.WriteLine("BC::Display"); } class DC : BC new public void Display() System.Console.WriteLine("DC::Display"); class Demo public static void Main() BC b; b = new BC(); b.Display(); b = new DC(); Output BC::Display
23
class BC { public void Display() System.Console.WriteLine("BC::Display"); } class DC : BC new public void Display() System.Console.WriteLine("DC::Display"); class TC : BC class Demo public static void Main() BC b; b = new BC(); b.Display(); b = new DC(); b = new TC(); Output BC::Display
24
Method Overriding Virtual and Override keywords 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 sub-classes 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 Sample code For complete details, please refer the following URL: 24
25
Method Overriding class BC { public virtual void Display()
System.Console.WriteLine("BC::Display"); } class DC : BC public override void Display() System.Console.WriteLine("DC::Display"); class Demo public static void Main() BC b; b = new BC(); b.Display(); b = new DC(); Output BC::Display DC::Display
26
class BC { public virtual void Display() System.Console.WriteLine("BC::Display"); } class DC : BC public override void Display() System.Console.WriteLine("DC::Display"); class TC : DC public new void Display() System.Console.WriteLine("TC::Display"); class Demo public static void Main() BC b; b = new TC(); b.Display(); Output DC::Display
27
Abstraction 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
28
Abstraction Abstract classes 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 Have no implementation Derived classes must override inherited abstract methods and properties to enable instantiation
29
Abstract base classes In C#, the abstract modifier is used to declare an abstract class
30
Abstract Classes Cannot Instantiated
abstract class Vehicle { } static void Main(string[] args) // Abstract Class cannot be instantiated Vehicle obj = new Vehicle(); // Shows Compilation Error.
31
Abstract Methods abstract class Vehicle { public abstract void Run(); } class Car : Vehicle public override void Run() Console.WriteLine("Run the Car"); class Bus : Vehicle Console.WriteLine("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.
32
Why must make everything abstract?
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
33
Interfaces An interface is a collection of method definitions (without implementations) and constant values. An interface is like a pure abstract base class Notes: A class that implements a particular interface must implement the members listed by that interface
34
Differences between Abstract Classes Vs. Interfaces
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
35
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.WriteLine("Hello Interfaces"); } interface abc void xyz(); Output Hello Interfaces Example (2) class Demo { public static void Main() System.Console.WriteLine("Hello Interfaces"); } interface abc Output Hello Interfaces
36
Example 3 class Demo { public static void Main()
System.Console.WriteLine("Hello Interfaces"); } interface abc int x; Output error Interfaces cannot contain fields
37
Example 4 { public static void Main()
System.Console.WriteLine("Hello Interfaces"); } interface abc void xyz() System.Console.WriteLine("In xyz"); Output error : 'abc.xyz()': interface members cannot have a definition
38
Example 5 class Demo : abc { public static void Main()
System.Console.WriteLine("Hello Interfaces"); xyz(); } public void xyz() System.Console.WriteLine("In xyz"); interface abc void xyz(); Output Hello Interfaces In xyz
39
Example 6 interface abc { void xyz(); } class Sample : abc
class Demo : abc { public static void Main() System.Console.WriteLine("Hello Interfaces"); Demo refDemo = new Demo(); refDemo.xyz(); Sample refSample = new Sample(); refSample.xyz(); } public void xyz() System.Console.WriteLine("In Demo :: xyz"); interface abc { void xyz(); } class Sample : abc public void xyz() System.Console.WriteLine("In Sample :: xyz"); Output In Demo :: xyz In Sample :: xyz
40
Multiple Inheritance 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. 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.
41
Implementing Multiple Interfaces
42
A Class cannot have multiple Base Classes
43
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 For complete details, please refer the following URL: 43
44
A file can declare multiple namespaces.
45
Namespaces Namespace CS415 Class A Class B Class C Namespace CS340
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 CS415 Class A Class B Class C Namespace CS340 Class A Class B Class C CS415.A… CS340.A…
46
Why Namespaces?? 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).
47
namespace FlatShapes { 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 * ; } public double Area get { return Radius * Radius * ; }
48
namespace Volumes { class Sphere : FlatShapes.Circle new public double Area get { return 4 * Radius * Radius * ; } } public double Volume get { return 4 * * Radius * Radius * Radius / 3; }
49
using System; using Volumes; using FlatShapes; class Exercise { static void Show(Circle round) Console.WriteLine("Circle Characteristics"); Console.WriteLine("Side: {0}", round.Radius); Console.WriteLine("Diameter: {0}", round.Diameter); Console.WriteLine("Circumference: {0}", round.Circumference); Console.WriteLine("Area: {0}", round.Area); } static void Show(Sphere ball) Console.WriteLine("\nSphere Characteristics"); Console.WriteLine("Side: {0}", ball.Radius); Console.WriteLine("Diameter: {0}", ball.Diameter); Console.WriteLine("Circumference: {0}", ball.Circumference); Console.WriteLine("Area: {0}", ball.Area); Console.WriteLine("Volume: {0}\n", ball.Volume);
50
This would produce: public static int Main() {
FlatShapes.Circle c = new FlatShapes.Circle(); Volumes.Sphere s = new Volumes.Sphere(); c.Radius = 20.25; Show(c); s.Radius = 20.25; Show(s); return 0; } This would produce: Circle Characteristics Side: Diameter: 51.1 Circumference: Area: Sphere Characteristics Area: Volume:
51
Indexers 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
53
Delegates 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
54
Declaring and Implementing a Delegate:
[access modifier] delegate Result_type Identifier([parameters]); Example: 1- public delegate int mon_delegate ( int val1, int val2); 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);
55
using system; class Class1 { public delegate int mon_delegate ( int val1, int val2); public Class1(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.WriteLine(“The Value max is :”+ ma); break; case 2: mon_delegate del_min= new mon_delegate(min); int mi = del_min(x,y); Console.WriteLine(“The Value min is :”+ mi); case 3: mon_delegate del_sum= new mon_delegate(sum); int s = del_sum(x,y); Console.WriteLine(“The sum is :”+ s);
56
case 4: mon_delegate del_mul= new mon_delegate(mul); int mu = del_mul(x,y); Console.WriteLine(“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; public int sum(int x,int y) return (x+ y); public int mul(int x,int y) return (x* y);
57
The value max is : 5 The value min is : 4 The sum is : 9
class Program { Static void Main(string[ ] args) int x=4,y=5; Class1 c1=new Class1(1,x,y); Class1 c2=new Class1(2,x,y); Class1 c3=new Class1(3,x,y); Class1 c4=new Class1(4,x,y); Console.ReadKey(); } The program output: The value max is : 5 The value min is : 4 The sum is : 9 The multip. is : 20
58
Summary Delegates provide dynamic run-time method invocation services
Inheritance allows a software developer to derive a new class from an existing one Derived class objects inherit members of base class 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
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.