Object-Oriented Programming: Objects
Object-Oriented Programming: Objects
Object-Oriented Programming: Objects
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."
Heap
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.
}
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
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.
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:
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.
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 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
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:
}
}
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)
{
}