Professional Documents
Culture Documents
Advanced OOP
Concepts in C#
Review
Review Contd
C# Simplified / Session 3 / 3 of 28
Objectives
Discuss Polymorphism
Use Interfaces
C# Simplified / Session 3 / 4 of 28
Polymorphism in C#
Polymorphism in C# Contd
C# Simplified / Session 3 / 6 of 28
Advantages of
Polymorphism
Polymorphism in C# Example
using System;
class Parent
{
public int MethodA()
{
return (MethodB()*MethodC());
}
public virtual int MethodB()
{
return(10);
}
public int MethodC()
{
return(20);
}
}
C# Simplified / Session 3 / 8 of 28
Polymorphism in C# Example
class Child : Parent
{
public override int MethodB()
{
return(30);
}
}
class PolymorphDemo
{
public static void Main()
{
Child ObjChild = new Child();
Console.WriteLine("The output is "
+ObjChild.MethodA());
}
}
C# Simplified / Session 3 / 9 of 28
Polymorphism in C# Output
C# Simplified / Session 3 / 10 of 28
Points to Remember
C# Simplified / Session 3 / 11 of 28
Relationship between
Polymorphism and
C#
enables polymorphism through
Inheritance
inheritance
Inheritance means a derived class gets state
and behaviour of the parent class.
Polymorphism means the right method
gets called, the one belonging to the actual
object that is being referenced
Polymorphism relies on inheritance to ensure
that no two classes respond identically to a
particular event.
C# Simplified / Session 3 / 12 of 28
C# Simplified / Session 3 / 13 of 28
C# Simplified / Session 3 / 14 of 28
class AbstractDemo
{
public static void Main()
{
DerivedClass objDerived = new
DerivedClass();
BaseClass objBase = objDerived;
objBase.MethodA();
objDerived.MethodB();
}
}
C# Simplified / Session 3 / 15 of 28
Interfaces
C# Simplified / Session 3 / 16 of 28
Interfaces
Example
public interface IFile
{
int delFile();
void disFile();
}
public class MyFile : IFile
{
public int delFile()
{
System.Console.WriteLine ("DelFile
Implementation!");
return(0);
}
public void disFile()
{
System.Console.WriteLine ("DisFile
Implementation!");
}
}
C# Simplified / Session 3 / 17 of 28
Interfaces - Output
class InterfaceDemo
{
public static void Main()
{
MyFile objMyFile = new MyFile();
objMyFile.disFile();
int retValue = objMyFile.delFile();
}
}
public class BaseforInterface
{
public void open()
{
System.Console.WriteLine ("This is the open method of
BaseforInterface");
}
}
C# Simplified / Session 3 / 18 of 28
C# Simplified / Session 3 / 19 of 28
C# Simplified / Session 3 / 20 of 28
C# Simplified / Session 3 / 21 of 28
Multiple Interfaces
C# Simplified / Session 3 / 22 of 28
C# Simplified / Session 3 / 23 of 28
C# Simplified / Session 3 / 24 of 28
Explicit Interface
C# Simplified / Session 3 / 25 of 28
C# Simplified / Session 3 / 26 of 28
Interface Inheritance
C# Simplified / Session 3 / 27 of 28
Summary
C# Simplified / Session 3 / 28 of 28