SlideShare a Scribd company logo
1 of 11
Download to read offline
:C#Zone
Week 6(according to IUB outline):-
---------------------------------------------------------------------------------
Implementing Object-Oriented Programming Techniques in C# Part-II
1. Using Polymorphism: Static Polymorphism (Overloading), Dynamic Polymorphism
(Overriding)
2. Abstract Classes
3. Using Interfaces.
---------------------------------------------------------------------------------
Any issue:umarfarooqworld@outlook.com
Ref: C#Corner Pick “N” Share :C#Notes
2 | P a g e “A room without books is like a body without a soul”
1. Polymorphism
1.1 Introduction
Polymorphism is a Greek word meaning "one name many forms". In other
words, one object has many forms or has one name with multiple
functionalities. "Poly" means many and "morph" means forms. Polymorphism
provides the ability to class multiple implementations with the same name. It is
one principle concept in Object Oriented Programming after encapsulation and
inheritance.
1.2 Types of Polymorphism
There are basically the following two types of polymorphism in C#:
ď‚· Static / Compile Time Polymorphism.
ď‚· Dynamic / Runtime Polymorphism.
1.2.1 Static or Compile Time Polymorphism
It is also known as Early Binding. Method overloading is an example of Static
Polymorphism. In Overloading, the method / function has the same name but
different signatures. It is also known as Compile Time Polymorphism because
the decision of which method is to be called is made at compile time.
Overloading is the concept in which method names are the same with a
different set of parameters
Ref: C#Corner Pick “N” Share :C#Notes
3 | P a g e “A room without books is like a body without a soul”
1.2.1.1 Example
Here the compiler checks the number of parameters passed and the type of
parameter and make the decision of which method to call and it throw an error if
no matching method is found.
In the following example the class has two methods with the same name "Add"
but with different input parameters (the first method has three parameters and
the second method has two parameters).
1. public class TestData
2. {
3. public int Add(int a, int b, int c)
4. {
5. return a + b + c;
6. }
7. public int Add(int a, int b)
8. {
9. return a + b;
10. }
11. }
12. class Program
13. {
14. static void Main(string[] args)
15. {
16. TestData dataClass = new TestData();
17. int add2 = dataClass.Add(45, 34, 67);
18. int add1 = dataClass.Add(23, 34);
19. }
20. }
Ref: C#Corner Pick “N” Share :C#Notes
4 | P a g e “A room without books is like a body without a soul”
1.2.2 Dynamic / Runtime Polymorphism
Dynamic / runtime polymorphism is also known as late binding. Here, the
method name and the method signature (number of parameters and
parameter type must be the same and may have a different implementation).
Method overriding is an example of dynamic polymorphism.
Method overriding can be done using inheritance. With method overriding it is
possible for the base class and derived class to have the same method name
and same something. The compiler would not be aware of the method
available for overriding the functionality, so the compiler does not throw an
error at compile time. The compiler will decide which method to call at runtime
and if no method is found then it throws an error.
1.2.2.1 Example
1. public class Drawing
2. {
3. public virtual double Area()
4. {
5. return 0;
6. }
7. }
8. public class Circle : Drawing
9. {
10. public double Radius { get; set; }
11. public Circle()
12. {
13. Radius = 5;
14. }
15. public override double Area()
16. {
17. return (3.14) * Math.Pow(Radius, 2);
18. }
19. }
20. public class Square : Drawing
21. {
22. public double Length { get; set; }
23. public Square()
24. {
25. Length = 6;
26. }
27. public override double Area()
28. {
29. return Math.Pow(Length, 2);
30. }
31. }
32. public class Rectangle : Drawing
33. {
34. public double Height { get; set; }
35. public double Width { get; set; }
36. public Rectangle()
37. {
38. Height = 5.3;
Ref: C#Corner Pick “N” Share :C#Notes
5 | P a g e “A room without books is like a body without a soul”
39. Width = 3.4;
40. }
41. public override double Area()
42. {
43. return Height * Width;
44. }
45. }
46. class Program
47. {
48. static void Main(string[] args)
49. {
50. Drawing circle = new Circle();
51. Console.WriteLine("Area :" + circle.Area());
52.
53. Drawing square = new Square();
54. Console.WriteLine("Area :" + square.Area());
55.
56. Drawing rectangle = new Rectangle();
57. Console.WriteLine("Area :" + rectangle.Area());
58. }
59. }
The compiler requires an Area() method and it compiles successfully but the right version of the Area() method
is not being determined at compile time but determined at runtime. Finally the overriding methods must have the
same name and signature (number of parameters and type), as the virtual or abstract method defined in the
base class method and that it is overriding in the derived class
VIRTUAL KEYWORD is used for achieving method overriding. In derived class, we want
to override the base class method then it should be declared virtual in base class.
Ref: C#Corner Pick “N” Share :C#Notes
6 | P a g e “A room without books is like a body without a soul”
2. Abstract Class
2.1 What is an Abstract Class?
The dictionary meaning of the word "abstract" is a thought or idea that has no physical existence and is
just conceptual. We can use the idea to build something of a physical existence. In the MSDN Library,
the "abstract" keyword indicates that the thing has a missing or incomplete implementation and must be
completed by others.
The abstract keyword can be used with classes, methods, properties, indexers and events. If we use the
abstract keyword with a class, it indicates that the class is intended to be a base class and can have
abstract methods (ideas) that must be implemented in a derived class (physical existence).
An abstract class is a special kind of class that has no implementation. It cannot be instantiated. Its
implementation logic is provided by the classes that derive from it. It can have both abstract as well as
non-abstract methods.
It is not compulsory to have only abstract methods in an abstract class. We can also have an abstract
class with only non-abstract methods.
2.2 Why do we need an Abstract Class?
With an Abstract Class, we can provide some kind of default functionality for all derived classes to
extend from. This is useful to avoid code duplication in many cases.
Abstract classes are also useful in the case of modifications to the project. If you plan on updating the
base class in your project, it is better to make the class abstract. Because you can define a functionality
in an abstract base class and automatically all the inheriting classes will have the same functionality
without disturbing the hierarchy.
2.3 Key Points
1. We cannot create an object of Abstract Class but we can create a reference of it.
1. using System;
2.
3. namespace AbstractClassDemo
4. {
5. abstract class absClass { }
6. class Program
7. {
8. public static void Main(string[] args)
9. {
10. //We can't do this
11. //absClass cls = new absClass();
12. //We can do this
13. absClass cls;
14. }
15. }
16. }
2. An inheritance between abstract to abstract classes is possible. We don't need to implement
abstract methods of the base abstract class into a derived abstract class. We can implement it later
in concrete classes.
1. using System;
2.
3. namespace AbstractClassDemo
4. {
5. abstract class absClassA
6. {
7. //Abstract Method
8. public abstract void SomeMethod();
9. }
10.
Ref: C#Corner Pick “N” Share :C#Notes
7 | P a g e “A room without books is like a body without a soul”
11. abstract class absClassB: absClassA //Abstract to Abstract Inheritance
12. {
13. }
14.
15. class Program: absClassB
16. {
17. public override void SomeMethod()
18. {
19. //Some Implementation Here
20. }
21.
22. public static void Main(string[] args)
23. {
24. }
25. }
26. }
3. An abstract class can never be sealed or static.
4. An abstract class can have abstract as well as non abstract methods.
5. The abstract keyword can be used with class, methods, properties, indexers and events.
6. Abstract members can only be declared inside an abstract class.
7. An abstract member cannot be static or private.
8. An abstract method cannot be marked virtual.
9. A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is
not possible.
10. Without an abstract class, we cannot implement the Template Method Pattern.
2.4 Example
1. using System;
2.
3. namespace AbstractClassDemo
4. {
5. abstract class iPhone
6. {
7. public void Call()
8. {
9. Console.WriteLine("Call Method: This method provides Calling features");
10. }
11. public abstract void Model();
12. }
13.
14. class iPhone5s: iPhone
15. {
16. public override void Model()
17. {
18. Console.WriteLine("Model: The model of this iPhone is iPhone5s");
19. }
20.
21. public void LaunchDate()
22. {
23. Console.WriteLine("Launch Date: This iPhone was launched on 20-September-
2013");
24. }
25. }
26.
27. class Program
28. {
Ref: C#Corner Pick “N” Share :C#Notes
8 | P a g e “A room without books is like a body without a soul”
29. static void Main(string[] args)
30. {
31. iPhone5s iphone5s = new iPhone5s();
32. iphone5s.Call();
33. iphone5s.Model();
34. iphone5s.LaunchDate();
35. Console.ReadKey();
36. }
37. }
38. }
3.Interface
ď‚· An interface looks like a class that can have a set of properties, methods, events and indexers, but has
no implementation. The interface does not have an implementation of properties, methods, events
and indexers because they are inherited by classes and structs, which must provide an implementation
for each interface member.
ď‚· An interface can be used to hide implementation details of classes from each other and it allows
various objects to interact easily. It provides a separation between interface and implementation.
ď‚· An interface is not only a contractual obligation to implement certain methods, properties, events and
indexes but also provides a very low coupling between two classes. Interfaces in C# are provided as a
replacement of multiple inheritances of classes because C# does not support multiple inheritances of
classes.
ď‚· Interfaces and abstract classes have similar purposes. Generally, an interface should be used when the
implementation of the members it defines is not fixed, or when it is known that a single class requires
the contents of several interfaces. Where the functionality of some members is fixed and the limited
multiple inheritance facility is not required, abstract classes may be more appropriate.
How to create an Interface
Syntax
Interface interface_name
{
}
3.1 Key points
1. An interface defines a signature of methods, events and indexes but not an implementation.
Example: An interface IVehicle that has a method "Speed()" with its definition/implementation.
interface IVehicle
{
double Speed(int distance, int hours)
{
double speed = 0.0d;
speed = distance / hours;
return speed;
}
}
We execute the above code and get an error such as:
Ref: C#Corner Pick “N” Share :C#Notes
9 | P a g e “A room without books is like a body without a soul”
Error : 'IVehicle.Speed(int, int)': interface members cannot have a definition
So the interface has only signature of methods, no implementation.
2. Interface members are public by default; there is no need to use an access specifier.
Example
An interface IVehicle that has a method "Speed()" signature and has a public access specifier.
interface IVehicle
{
public double Speed(int distance, int hours);
}
We execute the above code and get an error such as:
Error: The modifier 'public' is not valid for this item
So the interface members don't have any access specifier, by default they are public.
3. By default an interface is internal and we can't declare it private, protected or protected internal because it
is always inherited by classes or structs.
Example: An interface IVehicle that has a private access specifier:
private interface IVehicle
{
double Speed(int distance, int hours);
}
We execute the above code and get an error such as:
Error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected
internal
So by default the interface itself is internal and we can also use a public access specifier but can't use private,
protected and protected internal. One more thing is that class and struct also are by default internal as well as
interfaces.
4. An interface does not have fields; in other words we can't declare variables in an interface.
Example: An interface IVehicle that has two fields, one speed (not initialized) and another hours (initialized).
interface IVehicle
{
double speed;
decimal hours = 0.0m;
}
We execute the above code and get two errors, the same error for each field; see:
Error : Interfaces cannot contain fields
So we can't declare a field in the interface.
Ref: C#Corner Pick “N” Share :C#Notes
10 | P a g e “A room without books is like a body without a soul”
5. When an interface is inherited by a class or a struct then need to implement all members of the interface in
that class. An interface is inherited by a colon (:) sign on the class or struct.
Example
An interface "IVehicle" that has methods "Speed()" and "IVehicle" inherited by the Vehicle class.
interface IVehicle
{
double Speed(int distance, int hours);
}
class Vehicle:IVehicle
{
}
We execute the above code and get an error such as:
Error : 'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)'
So we should implement all members (method, properties etc) of the interface in classes that inherit an
interface.
6. Should use a public access specifier for inherited members from an interface to a class. By default all
members are public in interfaces but when we implement a method in a class we need to define it as public.
Example
An interface "IVehicle" that has a method "Speed()" signature and a class "Vehicle" that inherits the "IVehicle"
interface.
interface IVehicle
{
double Speed(int distance, int hours);
}
class Vehicle:IVehicle
{
double Speed(int distance, int hours)
{
double speed = 0.0d;
speed = distance / hours;
return speed;
}
}
We execute the above code and get an error such as:
Error : 'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)'. 'Vehicle.Speed(int, int)' cannot
implement an interface member because it is not public.
So we need to use a public access specifier when we implement an inherited interface member in a class
because all members are public in an interface.
Ref: C#Corner Pick “N” Share :C#Notes
11 | P a g e “A room without books is like a body without a soul”
7. We can't create an instance of an interface but we can declare a variable of a particular type interface.
Example: An interface "IVehicle" and a class "Vehicle" that inherits the "IVehicle" interface. See:
interface IVehicle
{
}
class Vehicle:IVehicle
{
IVehicle veh = new IVehicle();
}
We execute the above code and get an error such as:
Error: Cannot create an instance of the abstract class or interface 'IVehicle'
So we can't create an instance of the interface as well as abstract class because an interface is always inherited
but can create a variable of an interface type.
3.2 How can implement an Interface on a class
In the following code the "IVehicle" interface has a "Speed()" method signature and its inherited by the
"Vehicle" class so the speed() method implementation is in the derived class. After that in the "Program" class
a "Vehicle" instance calls the "Speed()" method:
using System;
namespace InterfaceExamples
{
interface IVehicle
{
double Speed(int distance, int hours);
}
class Vehicle : IVehicle
{
public double Speed(int distance, int hours)
{
double speed = 0.0d;
speed = distance / hours;
return speed;
}
}
class Program
{
static void Main(string[] args)
{
int distance =500,hours=2;
double speed = 0.0;
Vehicle objVehicle = new Vehicle();
speed = objVehicle.Speed(distance, hours);
Console.WriteLine("speed is {0}", speed);
Console.Read();
}
}
}

More Related Content

What's hot

Gsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comGsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comamaranthbeg8
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidemonsterr20
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidecritter13
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEWshyamuopten
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06HUST
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Pptmartha leon
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer iiIsabella789
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asmaAbdullahJana
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4Mahmoud Ouf
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notesInfinity Tech Solutions
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehosemichael.labriola
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 

What's hot (15)

Gsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comGsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.com
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Ppt
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii
 
1
11
1
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notes
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehose
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 

Similar to C#Zone Week 6: Implementing Object-Oriented Programming Techniques in C# Part-II

C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
polymorphism.ppt
polymorphism.pptpolymorphism.ppt
polymorphism.pptShubham79233
 
Lecture02-OOP-Review.ppt
Lecture02-OOP-Review.pptLecture02-OOP-Review.ppt
Lecture02-OOP-Review.ppt02LabiqaIslam
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesDurgesh Singh
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’svivek p s
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interfaceShubham Sharma
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Martin Chapman
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 

Similar to C#Zone Week 6: Implementing Object-Oriented Programming Techniques in C# Part-II (20)

C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Abstraction
Abstraction Abstraction
Abstraction
 
Abstraction
AbstractionAbstraction
Abstraction
 
polymorphism.ppt
polymorphism.pptpolymorphism.ppt
polymorphism.ppt
 
Lecture02-OOP-Review.ppt
Lecture02-OOP-Review.pptLecture02-OOP-Review.ppt
Lecture02-OOP-Review.ppt
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 

More from Umar Farooq

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
Linq in C#
Linq in C#Linq in C#
Linq in C#Umar Farooq
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-IUmar Farooq
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#Umar Farooq
 
Selection Sort
Selection Sort Selection Sort
Selection Sort Umar Farooq
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#Umar Farooq
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#Umar Farooq
 
Software process model
Software process modelSoftware process model
Software process modelUmar Farooq
 

More from Umar Farooq (9)

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-I
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Selection Sort
Selection Sort Selection Sort
Selection Sort
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
Matrix
MatrixMatrix
Matrix
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Software process model
Software process modelSoftware process model
Software process model
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

C#Zone Week 6: Implementing Object-Oriented Programming Techniques in C# Part-II

  • 1. :C#Zone Week 6(according to IUB outline):- --------------------------------------------------------------------------------- Implementing Object-Oriented Programming Techniques in C# Part-II 1. Using Polymorphism: Static Polymorphism (Overloading), Dynamic Polymorphism (Overriding) 2. Abstract Classes 3. Using Interfaces. --------------------------------------------------------------------------------- Any issue:umarfarooqworld@outlook.com
  • 2. Ref: C#Corner Pick “N” Share :C#Notes 2 | P a g e “A room without books is like a body without a soul” 1. Polymorphism 1.1 Introduction Polymorphism is a Greek word meaning "one name many forms". In other words, one object has many forms or has one name with multiple functionalities. "Poly" means many and "morph" means forms. Polymorphism provides the ability to class multiple implementations with the same name. It is one principle concept in Object Oriented Programming after encapsulation and inheritance. 1.2 Types of Polymorphism There are basically the following two types of polymorphism in C#: ď‚· Static / Compile Time Polymorphism. ď‚· Dynamic / Runtime Polymorphism. 1.2.1 Static or Compile Time Polymorphism It is also known as Early Binding. Method overloading is an example of Static Polymorphism. In Overloading, the method / function has the same name but different signatures. It is also known as Compile Time Polymorphism because the decision of which method is to be called is made at compile time. Overloading is the concept in which method names are the same with a different set of parameters
  • 3. Ref: C#Corner Pick “N” Share :C#Notes 3 | P a g e “A room without books is like a body without a soul” 1.2.1.1 Example Here the compiler checks the number of parameters passed and the type of parameter and make the decision of which method to call and it throw an error if no matching method is found. In the following example the class has two methods with the same name "Add" but with different input parameters (the first method has three parameters and the second method has two parameters). 1. public class TestData 2. { 3. public int Add(int a, int b, int c) 4. { 5. return a + b + c; 6. } 7. public int Add(int a, int b) 8. { 9. return a + b; 10. } 11. } 12. class Program 13. { 14. static void Main(string[] args) 15. { 16. TestData dataClass = new TestData(); 17. int add2 = dataClass.Add(45, 34, 67); 18. int add1 = dataClass.Add(23, 34); 19. } 20. }
  • 4. Ref: C#Corner Pick “N” Share :C#Notes 4 | P a g e “A room without books is like a body without a soul” 1.2.2 Dynamic / Runtime Polymorphism Dynamic / runtime polymorphism is also known as late binding. Here, the method name and the method signature (number of parameters and parameter type must be the same and may have a different implementation). Method overriding is an example of dynamic polymorphism. Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and same something. The compiler would not be aware of the method available for overriding the functionality, so the compiler does not throw an error at compile time. The compiler will decide which method to call at runtime and if no method is found then it throws an error. 1.2.2.1 Example 1. public class Drawing 2. { 3. public virtual double Area() 4. { 5. return 0; 6. } 7. } 8. public class Circle : Drawing 9. { 10. public double Radius { get; set; } 11. public Circle() 12. { 13. Radius = 5; 14. } 15. public override double Area() 16. { 17. return (3.14) * Math.Pow(Radius, 2); 18. } 19. } 20. public class Square : Drawing 21. { 22. public double Length { get; set; } 23. public Square() 24. { 25. Length = 6; 26. } 27. public override double Area() 28. { 29. return Math.Pow(Length, 2); 30. } 31. } 32. public class Rectangle : Drawing 33. { 34. public double Height { get; set; } 35. public double Width { get; set; } 36. public Rectangle() 37. { 38. Height = 5.3;
  • 5. Ref: C#Corner Pick “N” Share :C#Notes 5 | P a g e “A room without books is like a body without a soul” 39. Width = 3.4; 40. } 41. public override double Area() 42. { 43. return Height * Width; 44. } 45. } 46. class Program 47. { 48. static void Main(string[] args) 49. { 50. Drawing circle = new Circle(); 51. Console.WriteLine("Area :" + circle.Area()); 52. 53. Drawing square = new Square(); 54. Console.WriteLine("Area :" + square.Area()); 55. 56. Drawing rectangle = new Rectangle(); 57. Console.WriteLine("Area :" + rectangle.Area()); 58. } 59. } The compiler requires an Area() method and it compiles successfully but the right version of the Area() method is not being determined at compile time but determined at runtime. Finally the overriding methods must have the same name and signature (number of parameters and type), as the virtual or abstract method defined in the base class method and that it is overriding in the derived class VIRTUAL KEYWORD is used for achieving method overriding. In derived class, we want to override the base class method then it should be declared virtual in base class.
  • 6. Ref: C#Corner Pick “N” Share :C#Notes 6 | P a g e “A room without books is like a body without a soul” 2. Abstract Class 2.1 What is an Abstract Class? The dictionary meaning of the word "abstract" is a thought or idea that has no physical existence and is just conceptual. We can use the idea to build something of a physical existence. In the MSDN Library, the "abstract" keyword indicates that the thing has a missing or incomplete implementation and must be completed by others. The abstract keyword can be used with classes, methods, properties, indexers and events. If we use the abstract keyword with a class, it indicates that the class is intended to be a base class and can have abstract methods (ideas) that must be implemented in a derived class (physical existence). An abstract class is a special kind of class that has no implementation. It cannot be instantiated. Its implementation logic is provided by the classes that derive from it. It can have both abstract as well as non-abstract methods. It is not compulsory to have only abstract methods in an abstract class. We can also have an abstract class with only non-abstract methods. 2.2 Why do we need an Abstract Class? With an Abstract Class, we can provide some kind of default functionality for all derived classes to extend from. This is useful to avoid code duplication in many cases. Abstract classes are also useful in the case of modifications to the project. If you plan on updating the base class in your project, it is better to make the class abstract. Because you can define a functionality in an abstract base class and automatically all the inheriting classes will have the same functionality without disturbing the hierarchy. 2.3 Key Points 1. We cannot create an object of Abstract Class but we can create a reference of it. 1. using System; 2. 3. namespace AbstractClassDemo 4. { 5. abstract class absClass { } 6. class Program 7. { 8. public static void Main(string[] args) 9. { 10. //We can't do this 11. //absClass cls = new absClass(); 12. //We can do this 13. absClass cls; 14. } 15. } 16. } 2. An inheritance between abstract to abstract classes is possible. We don't need to implement abstract methods of the base abstract class into a derived abstract class. We can implement it later in concrete classes. 1. using System; 2. 3. namespace AbstractClassDemo 4. { 5. abstract class absClassA 6. { 7. //Abstract Method 8. public abstract void SomeMethod(); 9. } 10.
  • 7. Ref: C#Corner Pick “N” Share :C#Notes 7 | P a g e “A room without books is like a body without a soul” 11. abstract class absClassB: absClassA //Abstract to Abstract Inheritance 12. { 13. } 14. 15. class Program: absClassB 16. { 17. public override void SomeMethod() 18. { 19. //Some Implementation Here 20. } 21. 22. public static void Main(string[] args) 23. { 24. } 25. } 26. } 3. An abstract class can never be sealed or static. 4. An abstract class can have abstract as well as non abstract methods. 5. The abstract keyword can be used with class, methods, properties, indexers and events. 6. Abstract members can only be declared inside an abstract class. 7. An abstract member cannot be static or private. 8. An abstract method cannot be marked virtual. 9. A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is not possible. 10. Without an abstract class, we cannot implement the Template Method Pattern. 2.4 Example 1. using System; 2. 3. namespace AbstractClassDemo 4. { 5. abstract class iPhone 6. { 7. public void Call() 8. { 9. Console.WriteLine("Call Method: This method provides Calling features"); 10. } 11. public abstract void Model(); 12. } 13. 14. class iPhone5s: iPhone 15. { 16. public override void Model() 17. { 18. Console.WriteLine("Model: The model of this iPhone is iPhone5s"); 19. } 20. 21. public void LaunchDate() 22. { 23. Console.WriteLine("Launch Date: This iPhone was launched on 20-September- 2013"); 24. } 25. } 26. 27. class Program 28. {
  • 8. Ref: C#Corner Pick “N” Share :C#Notes 8 | P a g e “A room without books is like a body without a soul” 29. static void Main(string[] args) 30. { 31. iPhone5s iphone5s = new iPhone5s(); 32. iphone5s.Call(); 33. iphone5s.Model(); 34. iphone5s.LaunchDate(); 35. Console.ReadKey(); 36. } 37. } 38. } 3.Interface ď‚· An interface looks like a class that can have a set of properties, methods, events and indexers, but has no implementation. The interface does not have an implementation of properties, methods, events and indexers because they are inherited by classes and structs, which must provide an implementation for each interface member. ď‚· An interface can be used to hide implementation details of classes from each other and it allows various objects to interact easily. It provides a separation between interface and implementation. ď‚· An interface is not only a contractual obligation to implement certain methods, properties, events and indexes but also provides a very low coupling between two classes. Interfaces in C# are provided as a replacement of multiple inheritances of classes because C# does not support multiple inheritances of classes. ď‚· Interfaces and abstract classes have similar purposes. Generally, an interface should be used when the implementation of the members it defines is not fixed, or when it is known that a single class requires the contents of several interfaces. Where the functionality of some members is fixed and the limited multiple inheritance facility is not required, abstract classes may be more appropriate. How to create an Interface Syntax Interface interface_name { } 3.1 Key points 1. An interface defines a signature of methods, events and indexes but not an implementation. Example: An interface IVehicle that has a method "Speed()" with its definition/implementation. interface IVehicle { double Speed(int distance, int hours) { double speed = 0.0d; speed = distance / hours; return speed; } } We execute the above code and get an error such as:
  • 9. Ref: C#Corner Pick “N” Share :C#Notes 9 | P a g e “A room without books is like a body without a soul” Error : 'IVehicle.Speed(int, int)': interface members cannot have a definition So the interface has only signature of methods, no implementation. 2. Interface members are public by default; there is no need to use an access specifier. Example An interface IVehicle that has a method "Speed()" signature and has a public access specifier. interface IVehicle { public double Speed(int distance, int hours); } We execute the above code and get an error such as: Error: The modifier 'public' is not valid for this item So the interface members don't have any access specifier, by default they are public. 3. By default an interface is internal and we can't declare it private, protected or protected internal because it is always inherited by classes or structs. Example: An interface IVehicle that has a private access specifier: private interface IVehicle { double Speed(int distance, int hours); } We execute the above code and get an error such as: Error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal So by default the interface itself is internal and we can also use a public access specifier but can't use private, protected and protected internal. One more thing is that class and struct also are by default internal as well as interfaces. 4. An interface does not have fields; in other words we can't declare variables in an interface. Example: An interface IVehicle that has two fields, one speed (not initialized) and another hours (initialized). interface IVehicle { double speed; decimal hours = 0.0m; } We execute the above code and get two errors, the same error for each field; see: Error : Interfaces cannot contain fields So we can't declare a field in the interface.
  • 10. Ref: C#Corner Pick “N” Share :C#Notes 10 | P a g e “A room without books is like a body without a soul” 5. When an interface is inherited by a class or a struct then need to implement all members of the interface in that class. An interface is inherited by a colon (:) sign on the class or struct. Example An interface "IVehicle" that has methods "Speed()" and "IVehicle" inherited by the Vehicle class. interface IVehicle { double Speed(int distance, int hours); } class Vehicle:IVehicle { } We execute the above code and get an error such as: Error : 'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)' So we should implement all members (method, properties etc) of the interface in classes that inherit an interface. 6. Should use a public access specifier for inherited members from an interface to a class. By default all members are public in interfaces but when we implement a method in a class we need to define it as public. Example An interface "IVehicle" that has a method "Speed()" signature and a class "Vehicle" that inherits the "IVehicle" interface. interface IVehicle { double Speed(int distance, int hours); } class Vehicle:IVehicle { double Speed(int distance, int hours) { double speed = 0.0d; speed = distance / hours; return speed; } } We execute the above code and get an error such as: Error : 'Vehicle' does not implement interface member 'IVehicle.Speed(int, int)'. 'Vehicle.Speed(int, int)' cannot implement an interface member because it is not public. So we need to use a public access specifier when we implement an inherited interface member in a class because all members are public in an interface.
  • 11. Ref: C#Corner Pick “N” Share :C#Notes 11 | P a g e “A room without books is like a body without a soul” 7. We can't create an instance of an interface but we can declare a variable of a particular type interface. Example: An interface "IVehicle" and a class "Vehicle" that inherits the "IVehicle" interface. See: interface IVehicle { } class Vehicle:IVehicle { IVehicle veh = new IVehicle(); } We execute the above code and get an error such as: Error: Cannot create an instance of the abstract class or interface 'IVehicle' So we can't create an instance of the interface as well as abstract class because an interface is always inherited but can create a variable of an interface type. 3.2 How can implement an Interface on a class In the following code the "IVehicle" interface has a "Speed()" method signature and its inherited by the "Vehicle" class so the speed() method implementation is in the derived class. After that in the "Program" class a "Vehicle" instance calls the "Speed()" method: using System; namespace InterfaceExamples { interface IVehicle { double Speed(int distance, int hours); } class Vehicle : IVehicle { public double Speed(int distance, int hours) { double speed = 0.0d; speed = distance / hours; return speed; } } class Program { static void Main(string[] args) { int distance =500,hours=2; double speed = 0.0; Vehicle objVehicle = new Vehicle(); speed = objVehicle.Speed(distance, hours); Console.WriteLine("speed is {0}", speed); Console.Read(); } } }