You are on page 1of 22

Object-oriented programming

There are three widely used programming paradigms: procedural programming,


functional programming and object-oriented programming. C# supports both procedural and
object-oriented programming.
There are some basic programming concepts in OOP:

Abstraction

Polymorphism

Encapsulation

Inheritance

Objects
1. The software is divided into a number of small units called objects. The data and functions
are built around these objects.
2. The data of the objects can be accessed only by the functions associated with that object.
3. The functions of one object can access the functions of another object.
Objects are basic building blocks of a C# OOP program. An object is a combination of data
and methods. The data and the methods are called members of an object. In an OOP program,
we create objects. These objects communicate together through methods. Each object can
receive messages, send messages and process data.

Class
A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is mandatory to create a class for representing data.
A class is a blueprint of an object that contains variables for storing data and functions to
perform operations on the data.
A class will not occupy any memory space and hence it is only a logical representation of
data.
To create a class, you simply use the keyword "class" followed by the class name:

class Employee
{
}

Object
Objects are the basic run-time entities of an object oriented system. They may represent a
person,
a
place
or
any
item
that
the
program must
handle.
"An

object

is

software

bundle

of

related

variable

and

methods."

"An object is an instance of a class"


A class will not occupy any memory space. Hence to work with the data represented by the
class you must create a variable for the class, that is called an object.
When an object is created using the new operator, memory is allocated for the class in the
heap, the object is called an instance and its starting address will be stored in the object in
stack memory.
When an object is created without the new operator, memory will not be allocated in the
heap, in other words an instance will not be created and the object in the stack contains the
value null.
When an object contains null, then it is not possible to access the members of the class using
that object.
class Employee
{
}
Syntax to create an object of class Employee:
Employee objEmp = new Employee();

Stack and heap memory allocation


Stack

Local verable.or valu type


Ex:int.

Heap

Class varable.or reference type

All the programming languages supporting Object Oriented Programming will be supporting
these three main concepts:
Encapsulation
Inheritance
Polymorphism

Abstraction:
Abstraction is "To represent the essential feature without representing the background
details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or objects by providing relevant
information.
Abstraction is the process of hiding the working style of an object, and showing the
information of an object in an understandable manner.

Real-world Example of Abstraction


Suppose you have an object Mobile Phone.
Suppose you have 3 mobile phones as in the following:
Nokia 1400 (Features: Calling, SMS)
Nokia 2700 (Features: Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features: Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading
E-mails)
Abstract information (necessary and common information) for the object "Mobile Phone" is
that it makes a call to any number and can send SMS.
So that, for a mobile phone object you will have the abstract class as in the following:
Abstract class MobilePhone
{
public void Calling();
public void SendSMS();
}
public class Nokia1400 : MobilePhone
{

}
public class Nokia2700 : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
}
public class BlackBerry : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
public void Recording();
public void ReadAndSendEmails();
}

Abstraction means putting all the variables and methods in a class that are necessary.
For example: Abstract class and abstract method.
Abstraction is a common thing.

Example
1. If somebody in your collage tells you to fill in an application form, you will provide your
details, like name, address, date of birth, which semester, percentage you have etcetera.
2. If some doctor gives you an application to fill in the details, you will provide the details,
like name, address, date of birth, blood group, height and weight.
See in the preceding example what is in common?
3. Age, name and address, so you can create a class that consists of the common data. That is
called an abstract class.
That class is not complete and it can be inherited by other classes.

Encapsulation
Wrapping up a data member and a method together into a single unit (in other words class) is
called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data

related to an object into that object.


Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is
the property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
}
Encapsulation means hiding the internal details of an object, in other words how an object
does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the
abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from another object.
Hide the data for security such as making the variables private, and expose the property to
access the private data that will be public.
So, when you access the property you can validate the data and set it.
Example 1
class Demo
{
private int _mark;
public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}
Real-world Example of Encapsulation
Let's use as an example Mobile Phones and Mobile Phone Manufacturers.
Suppose you are a Mobile Phone Manufacturer and you have designed and developed a
Mobile Phone design (a class). Now by using machinery you are manufacturing Mobile
Phones (objects) for selling, when you sell your Mobile Phone the user only learns how to
use
the
Mobile
Phone
but
not
how
the
Mobile
Phone
works.
This means that you are creating the class with functions and by with objects (capsules) of
which you are making available the functionality of your class by that object and without the

interference

in

the

original

class.

Example 2
TV operation
It is encapsulated with a cover and we can operate it with a remote and there is no need to
open the TV to change the channel.
Here everything is private except the remote, so that anyone can access the remote to operate
and change the things in the TV.

C# Get Set Modifier


The get set accessor or modifier mostly used for storing and retrieving value from the
private field. The get accessor must return a value of property type where set accessor returns
void. The set accessor uses an implicit parameter called value. In simple word, the get
method used for retrieving value from private field whereas set method used for storing value
in private variables.
using System;
namespace Get_Set
{
class access
{
// String Variable declared as private
private static string name;
public void print()
{
Console.WriteLine("\nMy name is " + name);
}
public string Name //Creating Name property
{
get //get method for returning value
{
return name;
}
set // set method for storing value in name field.
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{

access ac = new access();


Console.Write("Enter your name:\t");
// Accepting value via Name property
ac.Name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}

ENCAPSULATION USING PROPERTIES:


Properties are a new language feature introduced with C#. Only a few languages
support this property. Properties in C# helps in protect a field in a class by reading and
writing to it. The first method itself is good but Encapsulation can be accomplished much
smoother with properties.
Now let's see an example.
using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);

return 0;
}
}
From the above example we see the usage of Encapsulation by using properties. The property
has two accessor get and set. The get accessor returns the value of the some property field.
The set accessor sets the value of the some property field with the contents of "value".
Properties can be made read-only. This is accomplished by having only a get accessor in the
property implementation.
Read only property:
using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d= new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;
}
}

In the above example we see how to implement a read-only property. The class
ReadDepartment has a Departname property that only implements a get accessor. It leaves
out the set accessor. This particular class has a constructor, which accepts a string parameter.
The Main method of the ReadDepartmain class creates a new object named d. The
instantiation of the d object uses the constructor of the ReadDepartment that takes a string
parameter. Since the above program is read-only, we cannot set the value to the field
departname and we only read or get the value of the data from the field. Properties can be

made also Write-only. This is accomplished by having only a set accessor in the property
implementation.
Write only property:
using system;
public class WriteDepartment
{
private string departname;
public string Departname
{
set
{
departname=value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d= new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}
In the above example we see how to implement a Write-only property. The class
WriteDepartment has now has a Departname property that only implements a set accessor. It
leaves out the get accessor. The set accessor method is varied a little by it prints the value of
the departname after it is assigned.
Encapsulation Access specifiers:

Public: Access to all code in the program


Private: Access to only members of the same class
Protected: Access to members of same class and its derived classes
Internal: Access to current assembly
Protected Internal: Access to current assembly and types derived from containing
class

Public Access Specifier


Public access specifier allows a class to expose its member variables and member functions
to other functions and objects. Any public member can be accessed from outside the class.

using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
public double length;
public double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
Output:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so they
can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly
without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed
from Main() using an instance of the Rectangle class, named r.

Private Access Specifier


Private access specifier allows a class to hide its member variables and member functions
from other functions and objects. Only functions of the same class can access its private
members. Even an instance of a class cannot access its private members.
The following example illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;
public void Acceptdetails()
{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:

Output:
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so
they
cannot
be
accessed
from
the
function
Main().
The
member
functions AcceptDetails() and Display() can access these variables. Since the member
functions AcceptDetails() and Display() are declared public, they can be accessed
from Main() using an instance of the Rectangle class, named r.
Protected Access Specifier
Protected access specifier allows a child class to access the member variables and member
functions of its base class. This way it helps in implementing inheritance. We will discuss
this in more details in the inheritance chapter.
Internal Access Specifier
Internal access specifier allows a class to expose its member variables and member functions
to other functions and objects in the current assembly. In other words, any member with
internal access specifier can be accessed from any class or method defined within the
application in which the member is defined.
The following program illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
internal double length;
internal double width;
double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());

}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Output:
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any
access specifier. Then what would be the default access specifier of a class member if we
don't mention any? It is private.
Protected Internal Access Specifier
The protected internal access specifier allows a class to hide its member variables and
member functions from other class objects and functions, except a child class within the same
application. This is also used while implementing inheritance.

Polymorphism:
Polymorphism means many forms (ability to take more than one form). In Polymorphism
poly means multiple and morph means forms so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in same
class or methods with same name and same parameters in different classes. Polymorphism
has ability to provide different implementation of methods that are implemented with same
name.

In Polymorphism we have 2 different types those are


- Compile Time Polymorphism (Called as Early Binding or Overloading or static
binding)
- Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)
Compile Time Polymorphism
Compile time polymorphism means we will declare methods with same name but different
signatures because of this we will perform different tasks with same method name. This
compile time polymorphism also called as early binding or method overloading.
Method Overloading or compile time polymorphism means same method names with
different signatures (different parameters)
Example
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but having different input parameters
this is called method overloading or compile time polymorphism or early binding.
Run Time Polymorphism
Run time polymorphism also called as late binding or method overriding or dynamic
polymorphism. Run time polymorphism or method overriding means same method names
with same signatures.

In this run time polymorphism or method overriding we can override a method in base class
by creating similar function in derived class this can be achieved by using inheritance
principle and using virtual &override keywords.
In base class if we declare methods with virtual keyword then only we can override those
methods in derived class using override keyword

Example
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
If we run above code we will get output like as shown below
Output
---------------------------------Derived Class
Derived Class

The word polymorphism means having many forms. In object-oriented programming


paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism the response to a function
is determined at the compile time. In dynamic polymorphism , it is decided at run-time.

Static Polymorphism
The mechanism of linking a function with an object during compile time is called early
binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. These are:

Function overloading

Operator overloading

We will discuss function overloading in the next section and operator overloading will be
dealt with in next chapter.
Function Overloading
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ only by
return type.
Following is the example where same function print() is being used to print different data
types:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");

Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++

Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation
of an interface. Implementation is completed when a derived class inherits from
it. Abstract classes contain abstract methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Please note the following rules about abstract classes:

You cannot create an instance of an abstract class

You cannot declare an abstract method outside an abstract class

When a class is declared sealed, it cannot be inherited, abstract classes cannot be


declared sealed.

The following program demonstrates an abstract class:


using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);

}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an inherited
class(es), you use virtual functions. The virtual functions could be implemented differently
in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this:
using System;
namespace PolymorphismApplication
{
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{
}

public override int area ()


{
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{
}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester
{
static void Main(string[] args)
{
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Rectangle class area:
Area: 70
Triangle class area:
Area: 25

You might also like