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();
}
}
}