You are on page 1of 39

Object Oriented Design

➔ First concept of object oriented programming is emerged at 60‘s.


➔ Smalltalk language which is introduced at 1972 was first object
oriented programming language.
➔ Smalltalk has defined essentials and rules of object oriented
programming.
➔ In 80’s C++ came out and made object oriented programming a de-
facto standard.
➔ C# and Java programming languages which are successors of C++,
has widespread usage nowadays.
OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
OOP Features
Object Oriented Programming (OOP) is a programming model where programs are organized around
objects and data rather than action and logic.

OOP allows decomposition of a problem into a number of entities called objects and then builds data
and functions around these objects. 

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
The software is divided into a number of small units called objects. The data and functions are built around these
objects.

The data of the objects can be accessed only by the functions associated with that object.

The functions of one object can access the functions of another 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 a software bundle of related variable and methods."

"An object is an instance of a class" .

Syntax to create an object of class Employee:

Employee objEmp = new Employee();


Example
An object consists of : 

•State: It is represented by attributes of an object. It also reflects the properties of an object.

•Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.

•Identity: It gives a unique name to an object and enables one object to interact with other objects.

Consider Dog as an object and see the below diagram for its identity, state, and behavior.
// C# program to illustrate the
// Initialization of an object
using System;

// Class Declaration
public class Dog {

// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// Property 1
public String GetName()
{
return name;
}

// Property 2
public String GetBreed()
{
return breed;
}
// Property 3
public int GetAge()
{
return age;
}

// Property 4
public String GetColor()
{
return color;
}

// Method 1
public String ToString()
{
return ("Hi my name is " + this.GetName()
+ ".\nMy breed, age and color are " + this.GetBreed()
+ ", " + this.GetAge() + ", " + this.GetColor());
}

// Main Method
public static void Main(String[] args)
{

// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
Console.WriteLine(tuffy.ToString());
}
}
Output: 
Hi my name is tuffy.
My breed, age and color are
papillon, 5, white
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,

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

If somebody in your college 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.

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?

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.
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.
➔ Technically in encapsulation, the variables or data of a class are hidden from any other class and can be
accessed only through any member function of own class in which they are declared.

➔ As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

➔ Encapsulation can be achieved by: Declaring all the variables in the class as private and using
C# Properties in the class to set and get the values of variables.
// C# program to illustrate encapsulation
using System;

public class DemoEncap {

// private variables declared


// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;

// using accessors to get and


// set the value of studentName
public String Name
{

get
{
return studentName;
}

set
{
studentName = value;
}

// using accessors to get and


// set the value of studentAge
public int Age
{

get
{
return studentAge;
}

set
{
studentAge = value;
}

// Driver Class
class GFG {

// Main Method
static public void Main()
{

// creating object
DemoEncap obj = new DemoEncap();

// calls set accessor of the property Name,


// and pass "Ankita" as value of the
// standard field 'value'
obj.Name = "Ankita";

// calls set accessor of the property Age,


// and pass "21" as value of the
// standard field 'value'
obj.Age = 21;

// Displaying values of the variables


Console.WriteLine("Name: " + obj.Name);
Console.WriteLine("Age: " + obj.Age);
}
}
Output:
Name: Ankita
Age: 21

Explanation: In the above program the class DemoEncap is encapsulated as the variables are declared as private.
To access these private variables we are using the Name and Age accessors which contains the get and set method
to retrieve and set the values of private fields. Accessors are defined as public so that they can access in other class.
Abstraction:
1. Process of picking the essence of an object you really need
2. In other words, pick the properties you need from the object Example:
a. TV - Sound, Visuals, Power Input, Channels Input.
b. Mobile - Button/Touch screen, power button, volume button, sim port.
c. Car - Steering, Break, Clutch, Accelerator, Key Hole.
d. Human - Voice, Body, Eye Sight, Hearing, Emotions.

Encapsulation:
3. Process of hiding the details of an object you don't need
4. In other words, hide the properties and operations you don't need from the object but are required for the object to work
properly Example:
a. TV - Internal and connections of Speaker, Display, Power distribution b/w components, Channel mechanism.
b. Mobile - How the input is parsed and processed, How pressing a button on/off or changes volumes, how sim will connect
to service providers.
c. Car - How turning steering turns the car, How break slow or stops the car, How clutch works, How accelerator increases
speed, How key hole switch on/of the car.
d. Human - How voice is produced, What's inside the body, How eye sight works, How hearing works, How emotions
generate and effect us.

ABSTRACT everything you need and ENCAPSULATE everything you don't need ;)
Inheritance
Inheritance

Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance
provides reusability by allowing us to extend an existing class.

The reason behind OOP programming is to promote the reusability of code and to reduce complexity
in code and it is possible by using inheritance.

The following are the types of inheritance in C#.


1) Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image
below, the class A serves as a base class for the derived class B.
2.)Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well
as the derived class also act as the base class to other class. In below image, class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C.
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one subclass. In below image, class A serves as a base class for the derived
class B, C, and D.
3)Multiple Inheritance(Through Interfaces):In Multiple inheritance, one class can have
more than one superclass and inherit features from all parent classes. Please note that C#
does not support multiple inheritance with classes. In C#, we can achieve multiple
inheritance only through Interfaces. In the image below, Class C is derived from interface A
and B.
5.)Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above
types of inheritance. Since C# doesn’t support multiple inheritance with classes, the
hybrid inheritance is also not possible with classes. In C#, we can achieve hybrid
inheritance only through Interfaces.
using System;

namespace Inheritance {

// base class
class Animal {

public string name;

public void display() {


Console.WriteLine("I am an animal");
}

// derived class of Animal


class Dog : Animal {

public void getName() {


Console.WriteLine("My name is " + name);
}
}

class Program {

static void Main(string[] args) {

// object of derived class


Dog labra = new Dog();

// access field and method of base class


labra .name = "Rohu";
labra .display();

// access method from own class


labra .getName();

Console.ReadLine();
}

}
}
Output:
I am an animal
My name is Rohu

Note:This is possible because the derived class inherits all fields and methods of the base
class.
Polymorphism

Polymorphism means one name, many forms.

One function behaves in different forms.

In other words, "Many forms of a single object is called Polymorphism."

Real-world Example of Polymorphism

Example 1

A teacher behaves students.

A teacher behaves his/her seniors.

Here teacher is an object but the attitude is different in different situations.

Example 2

A person behaves the son in a house at the same time that the person behaves an employee in an office.
Types of Polymorphism
There are two types of polymorphism in C#:

● Static / Compile Time Polymorphism.


● Dynamic / Runtime Polymorphism.

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 a 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.
Example

public class TestData


{
public int Add(int a, int b, int c)
{
return a + b + c;
}
public int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
TestData dataClass = new TestData();
int add2 = dataClass.Add(45, 34, 67);
int add1 = dataClass.Add(23, 34);
}
}
2.)Dynamic / Runtime Polymorphism

A polymorphism which exists at the time of execution of program is called


runtime polymorphism.

Example:method overriding.

Whenever we writing method in super class and sub class in such a way that
method name and parameter must be same called method overriding.
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.

Runtime polymorphism achieved using method overriding.


using System;

namespace Tutlane
{
// Base Class
public class BClass
{
public virtual void GetInfo()
{
Console.WriteLine("Learn C# Tutorial");
}
}
// Derived Class
public class DClass : BClass
{
public override void GetInfo()
{
Console.WriteLine("Welcome to Tutlane");
}
}
class Program
{
static void Main(string[] args)
{
DClass d = new DClass();
d.GetInfo();
BClass b = new BClass();
b.GetInfo();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
Virtual keyword:
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be
overridden in the derived class.

Why do we use override keyword in C#?

Override :
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited
method, property, indexer, or event.

You might also like