Four basic principles of Object- Oriented Programming

 

There are four basic principles in Object-Oriented programming: Encapsulation, Abstraction, Inheritance and Polymorphism.

 

Encapsulation

 

This is principle by which we hide data that we don’t want user to see and show data that we want them to see.

 

Classes have fields and methods. Fields are usually declared as private and get and set methods as public. Which means that users can access those methods but cannot access fields directly.

 

  Example:

     class Person{

        private string name;

        public string Name{

                     get {return name; }

                     set {name = value; }

        }

    }

Abstraction: 

Abstraction in OOP is used to hide implementation details. It hides and handles complex logic from the user. User can further implement more complex logic on top of abstraction that is already provided. User will know what that abstractions does but does not need to know how it is done.

Abstraction can be seen in the real world all the time, we just don’t think of it in that way. One of the examples is when we interact with our phones. All we do is press a button and we make a call. In reality a lot of things happen under the hood that we maybe don’t know or don’t need to know. That is abstraction and it is applied as principle in OOP as well.

 

Example: 

abstract class Animal(){

           public abstract void animalSound();

}

class Cat : Animal{

             public override void animalSound(){

                          Console.WriteLine(“Cat meows”);

              }

}

class Dog : Animal{

          public override void animalSound(){

                       Console.WriteLine(“Dog barks”);

           }

}

Inheritance:

When we are creating classes often times they share some logic. Now, we can write the exact same logic in both classes, or we can take that logic into separate class and use it in every class that requires that logic. 

Example:

class Vehicle{

           public string name;

}

class Car : Vehicle{

            …

}

Now class Car has it’s own fields and methods, but it can also access all methods of Vehicle class.

Polymorphism:

This literally means “many shapes”. In OOP this means and that programmers can change the way that something works by changing the way it is done or just some parts of it. Polymorphism can be static and dynamic. Static is achieved by method overloading, and dynamic by method overriding.

 

Example for method overloading:

it is better to overload one method than to write two methods that do the same thing.

 

static int Add(int x, int y){

          return x + y;

}

static double Add(double x, double y){

return x + y;

}

Example of method overriding:

We override methods to tailor it’s functionality to our needs.

 

public string Name {get; set; }

public override string ToString(){

return “Person: ” + Name;

}