You are on page 1of 21

Encapsulation binds together the data and functions that manipulate the data, keeping

it safe from interference and misuse.

Real World Example: Every time you log into your email account( GMailGmail, Yahoo,
Hotmail or official mail), you have a whole lot of processes taking place in the backend,
that you have no control over. So yourTherefore your password, would probably be
retrieved in an encyrpted encrypted form, verified and only then you are given access.
You do not have any control, over how the password is verified, and this keeps it safe
from misuse.

Abstraction is a process of hiding the implementation from the user, only the
functionality is exposed here. So you are aware only of what the application does, not
how it does it.

Real World Example: When you log into your email, compose and send a mail. Again
there is a whole lot of background processing involved, verifying the recipient, sending
request to the email server, sending your email. Here you are only interested in
composing and clicking on the send button. What really happens when you click on the
send button, is hidden from you.

For example, TV remote is an object. Users are provided with only interface which is
nothing but keys. Users only know which key to press for what function. User will not
know what happens inside when we press the key..

Implementation of Abstraction

To implement abstraction let's take an example of a car. We knows


a car, Car is made of name of car, color of car, steering, gear, rear
view mirror, brakes, silencer, exhaust system, diesal engine, car
battery, car engine and other internal machine details etc.

Now lets think in terms of Car rider or a person who is riding a car.
So to drive a car what a car rider should know from above category
before he starts a car driving.

Necessary things means compulsary to know before starting a car


1. Name of Car
2. Color of Car
3. Steering
4. Rear View Mirror
5. Brakes
6. Gear

Unnecessary things means  not that compulsary to know for a Car


rider

1. Internal Details of a Car


2. Car Engine
3. Diesal Engine
4. Exhaust System
5. Silencer

Now above same thing let me put in the coding style using C#

public class Car

private string _nameofcar = "My Car";


private string _colorofcar = "Red";

public string NameofCar

set

_nameofcar = value;
}
get
return _nameofcar;
}
}

public string ColorofCar

set

_colorofcar = value;
}
get

return _colorofcar;
}
}

public void Steering()

Console.WriteLine("Streering of Car");
}

public void RearViewMirror()

Console.WriteLine("RearViewMirror of Car");
}

public void Brakes()

Console.WriteLine("Brakes of Car");
}
public void Gear()
Console.WriteLine("Gear of Car");
}

private void InternalDetailsofCar()

Console.WriteLine("InternalDetailsofCar of Car");
}

private void CarEngine()

Console.WriteLine("CarEngine of Car");
}

private void DiesalEngine()

Console.WriteLine("DiesalEngine of Car");
}

private void ExhaustSystem()

Console.WriteLine("ExhaustSystem of Car");
}

private void Silencer()

Console.WriteLine("Silencer of Car");
}

}
As you can see from above code that necessary methods and
properties exposed by using "public" access modifier and
unnecessary methods and properties (not compulsary) hidden by
using "private" access modifier.
 

As you see to achieve abstraction we used access modifier "public"


to expose some methods and properties to outside the class or
world.

As you see to achieve abstraction we used access modifier "private"


to hide some methods and properties from outside the class or
world.

Finally lets check by creating an object of above class "Car" in our


main program of a console application and by using object lets see
weather we are getting all exposed necessary methods and
properties.
 

class Program

static void Main(string[] args)

Car objCar = new Car();

}
}

Conclusion

Sucessfully we have exposed necessary methods and properties to


outside the world or class. This is how we need to implement
abstraction or we can achieve abstraction in our code or application.

Real-time Examples of Encapsulation

Real-time Example 1:
School bag is one of the most real examples of Encapsulation. School bag can
keep our books, pens, etc.

Real-time Example 2: 

When you log into your email accounts such as Gmail, Yahoo mail, or Rediff
mail, there is a lot of internal processes taking place in the backend and you
have no control over it.

When you enter the password for logging, they are retrieved in an encrypted form
and verified and then you are given the access to your account. You do not have
control over it that how the password has been verified. Thus, it keeps our
account safe from being misused.

Real-time Example 3: 


Suppose you have an account in the bank. If your balance variable is declared as
a public variable in the bank software, your account balance will be known as
public, In this case, anyone can know your account balance. So, would you like
it? Obviously No. 

So, they declare balance variable as private for making your account safe, so
that anyone cannot see your account balance. The person who has to see his
account balance, he will have to access private members only through methods
defined inside that class and this method will ask your account holder name or
user Id, and password for authentication. 

Thus, We can achieve security by utilizing the concept of data hiding. This is
called Encapsulation.

Advantages of Encapsulation

There are following advantages of encapsulation


1. The encapsulated code is more flexible and easier to change with new
requirements.
2. It prevents the other classes to access the private fields.

3. Encapsulation allows modifying implemented code without breaking others


code who have implemented the code.

4. It keeps the data and codes safe from external inheritance. Thus,
Encapsulation helps to achieve security.

5. It improves the maintainability of the application.


6. If you don't define the setter method in the class then the fields can be made
read-only.
7. If you don't define the getter method in the class then the fields can be made
write-only.

Disadvantages of Encapsulation

The main disadvantage of the encapsulation is it increases the length of the code
and slow shutdown execution.

A constructor is a special method that is used to initialize a newly created object and is called
just after the memory is allocated for the object.

i.e Consider human as a class. The birth of a child is like initialising an object for that
class.

There is no kid in this world without a name. So naming ceremony is the functionality
inside a constructor, which will be done at the time of initialisation. Hence every kid gets
a name, necessarily!

Overloading Methods. A major topic in OOP is overloading methods, which lets you


define the same method multiple times so that you can call them with different argument
lists (a method's argument list is called its signature)
Overloading:  Consider the basic human function of speaking!

Assume, you are supposed just perform the function of talking. Say, you have to tell the
story of your day, to a total stranger. Your function will get over pretty quickly. Say, now
you are telling the same to your beloved. You will go through more details as compared
to the previous one. What has happened here, is, you have performed the same
function, but based on the parameter, stranger/beloved, your way of implementing the
function changed!
1. class You
2. {
3. void talk(Stranger obj)
4. {
5. sysout("Hi, my day was great!");
6. }
7. void talk(Beloved obj)
8. {
9. sysout("Hi, my day was great! You won't believe what happened
today! Blah!Blah!Blah!Blah!Blah!Blah!Blah!Blah!Blah!Blah! ");
10. }
11. }

Method Overriding is a technique that allows the invoking of functions from another class
(base class) in the derived class. Creating a method in the derived class with the same
signature as a method in the base class is called as method overriding.

Overriding:  Happens in the inheritance hierarchy!

We learn a lot from our parents! We learn to cook to some extent. The same delicacy
with same ingredients is prepared by your mother with a different taste and you with a
different taste (assuming). That is overriding, same function (cooking), same parameters
(ingredients), but different algorithms (cooking style).

Or, your learnt driving from you dad! But you both drive the same vehicle differently!
That is overriding.
1. class Father
2. {
3. void drive()
4. {
5. //drive cautiously :-)
6. }
7. }
8. class You
9. {
10. void drive()
11. {
12. //drive rash! :P
13. }
14. }
Programming perspective:

Here, the practical example would be,


1. interface Vehicle
2. {
3. void search(int number);
4. void search(String ownerName);
5. ...
6. }
7.  
8. class Pulsar implements Vehicle
9. {
10. public:
11. void search(int number) {}
12. void search(String ownerName) {}
13. ...
14. }
15.  
16. class RangeRover implements Vehicle
17. {
18. public:
19. void search(int number) {}
20. void search(String ownerName) {}
21. ...
22. }
23.  
24. public class Demo
25. {
26. public static void main(String[] args)
27. {
28. Vehicle obj = new Pulsar();
29. // calls the methods in Pulsar class
30. obj->search(1234);
31. obj->search("Siddharth");
32.
33. // this will call methods from RangeRover class
34. obj = new RangeRover();
35. obj->search(1234);
36. obj->search("Siddharth");
37. }
38. }
Inheritance is a very important aspect of Object Oriented Programming. It allows a class
to inherit all the properties of another class. Let’s discuss this topic in detail.

WHAT IS INHERITANCE?
Inheritance is one of the most important pillars of Object Oriented Programming.
Inheritance allows a class to access all the property of the Base class and also Base
class can have its own behaviour. Using Inheritance a class can be act as a template
for other classes. A class that allows inheritance is called as Base Class and the class
that inherits other class is called as derived class.

REAL WORLD EXAMPLE OF INHERITANCE:


An example of Inheritance that exists in the real world is Shape class, which is a base
class and its derived class can be Triangle, Rectangle and Square.
The basic concept of Inheritance is around IS-A relationship. For Example, Triangle is a
Shape.
WHEN SHOULD WE USE INHERITANCE?
I think we got some basic knowledge of Inheritance with an example. Now the point is
when we should use Inheritance. As I told you the idea of Inheritance is around IS-A
relationship. There are two types of relationships between classes:

 IS-A Relationship.
 HAS-A Relationship

Inheritance is used when your classes have IS-A Relationship. Such as Triangle IS-


A Shape. A Rectangle is a Shape. Suppose I have a class that calculates the area of
the shape then the relationship between the Shape and ShapeArea will be HAS-A.
Disadvantages of inheritance: The main disadvantage of the inheritance is that the
two classes(base class and super class) are tightly coupled that is the classes are
dependent on each other. If the functionality of the base class is changed then the
changes have to be done on the child classes also.

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.

The virtual keyword is used to modify a method, property, indexer, or event declaration and
allow for it to be overridden in a derived class. For example, this method can be overridden
by any class that inherits it:

When a virtual method is invoked, the run-time type of the object is checked for an
overriding member. The overriding member in the most derived class is called, which might
be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.


You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

Singleton Pattern is one of the best-known patterns in software engineering.


Essentially, a singleton is a class which only allows a single instance of itself to be
created, and usually gives simple access to that instance. Most commonly, singletons
don't allow any parameters to be specified when creating the instance - as otherwise a
second request for an instance but with a different parameter could be problematic!

Static method in C# is a method that keeps only one copy of the method at the Type level, not the
object level. That means, all instances of the class share the same copy of the method and its data. The
last updated value of the method is shared among all objects of that Type.

1. A static method can be invoked directly from the class level

2. A static method does not require any class object

3. Any main() method is shared through the entire class scope so it always appears with static
keyword.

Partial Classes in C#

A partial class is a special feature of C#. It provides a special ability to implement the
functionality of a single class into multiple files and all these files are combined into a
single class file when the application is compiled. A partial class is created by using
a partial keyword. This keyword is also useful to split the functionality of methods,
interfaces, or structure into multiple files.
Syntax :
public partial Clas_name
{
// code
}
Important points:

 When you want to chop the functionality of the class, method, interface, or
structure into multiple files, then you should use partial keyword and all the files
are mandatory to available at compile time for creating final file.
 The partial modifier can only present instantly before the keywords like struct,
class, and interface.
 Every part of the partial class definition should be in the same assembly
and namespace, but you can use different source file name.
 Every part of the partial class definition should have the same accessibility like
private, protected, etc.
 If any part of the partial class is declared as an abstract, sealed, or base, then
the whole class is declared of the same type.
 The user is also allowed to use nested partial types.
 Dissimilar part may have dissimilar base types, but the final type must inherit all
the base types.
Example: Here, we are taking a class named as Geeks and split the definition of Geeks
class into two different files named as Geeks1.cs, and Geeks2.cs as shown below:

In Geeks1.cs, and Geeks2.cs, a partial class is created using the partial keyword and
each file contains different functionality of Geeks class as shown below.
Geeks1.cs
filter_none
brightness_4
public partial class Geeks {
    private string Author_name;
    private int Total_articles;
  
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
}
Geeks2.cs
filter_none
brightness_4
public partial class Geeks {
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}
When we execute the above code, then compiler combines Geeks1.cs and Geeks2.cs into a
single file, i.e. Geeks as shown below.
Geeks This class may contain the Main Method. For simplicity, here Main() method is
not included.
filter_none
brightness_4
public class Geeks {
    private string Author_name;
    private int Total_articles;
  
    public Geeks(string a, int t)
    {
        this.Authour_name = a;
        this.Total_articles = t;
    }
  
    public void Display()
    {
        Console.WriteLine("Author's name is : " + Author_name);
        Console.WriteLine("Total number articles is : " + Total_articles);
    }
}
Advantages :
 With the help of partial class multiple developers can work simultaneously on the
same class in different files.
 With the help of partial class concept you can split the UI of design code and the
business logic code to read and understand the code.
 When you were working with automatically generated code, the code can be
added to the class without having to recreate the source file like in Visual studio.
 You can also maintain your application in an efficient manner by compressing
large classes into small ones.

Partial Methods in C#
C# contains a special method is known as a partial method, which contains declaration
part in one partial class and definition part in another partial class or may contain both
declaration and definition in the same partial class.
Basically, partial methods exist in the partial class, or in the struct. A partial method may
or may not contain implementation if a partial method doesn’t contain an implementation
in any part then the compiler will not create that method in the final class or driver class.
A partial method is declared with the help of the partial keyword as shown below.
Syntax:
partial void method_name
{
// Code
}
Important Points:

 The declaration of the partial method must begin with partial modifier.
 The partial method may contain ref.
 The partial method does not contain out parameters.
 It is implicitly private method.
 It can be a static method.
 Partial method is generic.
 It can have only void return type.
 A partial method is created only in partial class or in partial struct.
Example: We have a class named as Circle. The functionality of the Circle class is
chopped into two different files named as circle1.cs and circle2.cs.
These circle1.cs and circle2.cs files contain the partial class of the Circle class and
partial method, i.e area. The circle1.cs file contains the declaration of the partial area()
method and circle2.cs file contains the implementation of the area method as shown
below:
circle1.cs
filter_none
brightness_4
public partial class Circle {

  

    // This file only contains

    // declaration of partial method

    partial void area(int p);

  

    public void Display()

    {

        Console.WriteLine("Example of partial method");

    }

}
circle2.cs
filter_none
brightness_4
public partial class Circle {

  

    public void newarea(int a)

    {

        area(int a);

    }

  

    // This is the definition of

    // partial method

    partial void area(int r)

    {

        int A = 3.14 * r * r;

        Console.WriteLine("Area is : {0}", A);

    }

When we execute the above code, then compiler combines circle1.cs and circle2.cs into


a single file, i.e. circle as shown below.
circle
filter_none
brightness_4
public class Circle {

  

    public void Display()

    {

        Console.WriteLine("Example of partial method");

    }

  

    public void newarea(int a)


    {

        area(int a);

    }

  

    private void area(int r)

    {

        int A = 3.14 * r * r;

        Console.WriteLine("Area is : {0}", A);

    }

Composition

Inheritance is a hierarchy of relationships between objects. For example, car is a vehicle. So,

class Vehicle

//.....

class Car : Vehicle

//......

This denotes "is-a" relationship between objects. "Car is a vehicle".

Where as, Composition denotes "is-a-part-of" relationship between objects. For example,

class Engine

//....
}

class Car

Engine engine = new Engine();

//.....

Here Engine is-a-part-of Car.

Composition and inheritance are two concepts which has to be applied at appropriate scenarios.

Interface

When to use
1. Need to provide common functionality to unrelated classes.
2. Need to group objects based on common behaviors.
3. Need to introduce polymorphic behavior to classes since a class can
implements more than one interfaces.
4. Need to provide more abstract view to a model which is unchangeable.
5. Need to create loosely coupled components, easily maintainable and
pluggable components (like log4net framework for logging) because
implementation of an interface is separated from itself.

Disadvantage of Interface
1. The main issue with an interface is that when you add a new members to its,
then you must implement those members within all of the classes which
implement that interface.
2. Interfaces are slow as these required extra in-direction to find corresponding
method in in the actual class.

You might also like