Object Oriented Programming With A Real-World Scenario

In interviews, young programmers are asked for a real-world scenario explaining OOP and many fail to answer. This is the reason I am writing this article. This article is mainly intended for the audience who knows the Object Oriented Programming (OOP) concept theoretically but is unable to link it with the real world & programming world.

Man

We write programs to solve our problems and get our work done.

Object Oriented Programming is considered as a design methodology for building non-rigid software. In OOPS, every logic is written to get our work done but represented in the form of Objects. OOP allows us to break our problems into small units of work that are represented via objects and their functions. We build functions around objects.

Four features of OOP

There are mainly four pillars (features) of OOP. If all of these four features are presented in programming, the programming is called Object Oriented Programming.

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Let's consider an example explaining each of these pillars so you can better understand Object Oriented Programming.

Before that, we need to know something.

When we think of a mobile phone as an object, the basic functionality for which it was invented were Calling & Receiving a call & Messaging. But nowadays thousands of new features and models have been added and the features and number of models are still growing.

Mobiles

Samsung nokia iphone

In the above diagram, each brand (Samsung, Nokia, iPhone) has its list of features along with basic functionality of dialing, receiving a call, and messaging.

Objects

Any real-world entity which can have some characteristics or which can perform some tasks is called an Object. This object is also called an instance i.e. a copy of an entity in a programming language. If we consider the above example, a mobile manufacturing company can be an object. Each object can be different based on its characteristics. For example, here are two objects.

Mobile mbl1 = new Mobile();
Mobile mbl2 = new Mobile();

Class

A class in OOP is a plan which describes the object. We call it a blueprint of how the object should be represented. Mainly a class would consist of a name, attributes, and operations. Considering the above example, the Mobile can be a class, that has some attributes like Profile Type, IMEI Number, Processor, and some more. It can have operations like Dial, Receive, and SendMessage.

Some OOPS principles need to be satisfied while creating a class. This principle is called SOLID where each letter has some specification. I won't be going into these points deeper. A single line of each explanation may clear you with some points.

  1. SRP (The Single Responsibility Principle): A class should have one, and only one responsibility
  2. OCP (The Open Closed Principle): You should be able to extend a class's behavior, without modifying it. (Inheritance)
  3. LSP (The Liskov Substitution Principle): Derived classes must be substitutable for their base classes. (Polymorphism)
  4. ISP (The Interface Segregation Principle): Make a finely chopped interface instead of a huge interface as clients cannot be forced to implement an interface that they don't use.
  5. DIP (The Dependency Inversion Principle): Depend on abstractions, not on concretions. (Abstraction)

If you want to learn more about SOLID principles, check out SOLID Architectural Pattern with Real World Example.

Now, let's take a look at our class. A typical class based on the above discussion looks like the following in Visual Studio:

Methods

In C# programming language, a class has members. These members are called properties, methods, fields, constructors, destructors, events, and so on.

In code, the Mobile class looks like the following.

public class Mobile   
{   
    private string IEMICode { get; set; }   
    public string SIMCard { get; set; }   
    public string Processor { get; }   
    public int InternalMemory { get; }   
    public bool IsSingleSIM { get; set; }   

    public void GetIEMICode()   
    {   
        Console.WriteLine("IEMI Code - IEDF34343435235");   
    }   

    public void Dial()   
    {   
        Console.WriteLine("Dial a number");   
    }   

    public void Receive()   
    {   
        Console.WriteLine("Receive a call");   
    }   

    public virtual void SendMessage()   
    {   
        Console.WriteLine("Message Sent");   
    }   
}  

Abstraction

Abstraction allows us to expose limited data and functionality of objects publicly and hide the actual implementation. It is the most important pillar in OOPS. In our example of Mobile class and objects like Nokia, Samsung, and iPhone.

Some features of mobiles

  1. Dialing a number calls some method internally that concatenates the numbers and displays it on screen but what is it doing we don’t know.
  2. Clicking on the green button sends signals to the calling person's mobile but we are unaware of how it is doing.

This is called abstraction. In classes, we can create methods that can be called and used by the users of the class but users will have no idea what these methods do internally.

public void Dial()  
{  
    //Write the logic  
    Console.WriteLine("Dial a number");  
}  

Encapsulation

Encapsulation

Encapsulation is defined as the process of enclosing one or more details from the outside world through access rights. It says how much access should be given to particular details. Both Abstraction & Encapsulation work hand in hand because Abstraction says what details are to be made visible and Encapsulation provides the level of access right to that visible details. i.e. – It implements the desired level of abstraction.

Talking about Bluetooth which we usually have in our mobile. When we switch on Bluetooth, I can connect to another mobile or Bluetooth-enabled device but I'm not able to access the other mobile features like dialing a number, accessing inbox, etc. This is because the Bluetooth feature is given some level of abstraction.

Another point is when mobile A is connected with mobile B via Bluetooth whereas mobile B is already connected to mobile C then A is not allowed to connect to C via B. This is because of accessibility restrictions.

In C#, a class has access modifiers such as public, private, protected, and internal. These access modifiers allow properties and methods to be exposed or restricted to the outside world.

private string IMEICode = "76567556757656";  

Polymorphism

Polymorphism can be defined as the ability to use the same name for doing different things. More precisely we say it as 'many forms of single entity'. This plays a vital role in the concept of OOPS.

Let's say Samsung mobile has a 5MP camera available i.e. – it is having the functionality of CameraClick(). Now the same mobile has Panorama mode available in the camera, so functionality would be the same but with mode. This type is said to be Static polymorphism or Compile-time polymorphism. See the example below.

public class Samsumg : Mobile  
{  
    public void GetWIFIConnection()  
    {  
        Console.WriteLine("WIFI connected");  
    }  
  
    //This is one mwthod which shows camera functionality  
    public void CameraClick()  
    {  
        Console.WriteLine("Camera clicked");  
    }  
  
    //This is one overloaded method which shows camera functionality as well but with its camera's different mode(panaroma)  
    public void CameraClick(string CameraMode)  
    {  
        Console.WriteLine("Camera clicked in " + CameraMode + " Mode");  
    }  
}  

Compile time polymorphism the compiler knows which overloaded method it is going to call.

The compiler checks the type and number of parameters passed to the method and decides which method to call and it will give an error if there are no methods that match the method signature of the method that is called at compile time.

Another point where that SendMessage was intended to send a message to a single person at a time but suppose Nokia had given provision for sending a message to a group at once. i.e. - Overriding the functionality to send a message to a group. This type is called Dynamic polymorphism or Runtime polymorphism.

For overriding you need to set the method, which can be overridden to virtual & its new implementation should be decorated with the override keyword.

public class Nokia : Mobile  
{  
     public void GetBlueToothConnection()  
     {  
         Console.WriteLine("Bluetooth connected");  
     }  
   
     //New implementation for this method which was available in Mobile Class  
     //This is runtime polymorphism  
     public override void SendMessage()  
     {  
         Console.WriteLine("Message Sent to a group");  
     }  
}  

By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.

Inheritance

Inheritance

Inheritance is the ability to extend the functionality from the base entity to a new entity belonging to the same group. This will help us to reuse the functionality that was already defined before and extend it into a new entity.

Considering the example, the above figure 1.1 itself shows what is inheritance. Basic Mobile functionality is to send a message, dial, and receive a call. So the brands of mobile are using this basic functionality by extending the mobile class functionality and adding new features to their respective brand.

Four types of inheritance

There are mainly 4 types of inheritance,

  1. Single level inheritance
  2. Multi-level inheritance
  3. Hierarchical inheritance
  4. Hybrid inheritance
  5. Multiple inheritance

Single level inheritance

In Single-level inheritance, there is a single base class & a single derived class i.e. - A base mobile feature is extended by the Samsung brand.

Single inheritance

Multilevel inheritance

In Multilevel inheritance, there is more than one single level of derivation. i.e. - After base features are extended by the Samsung brand. Now Samsung brand has manufactured its new model with newly added features or advanced OS like Android OS, v4.4.2 (KitKat). From generalization, getting into more specification.

Multiple inheritance

Hierarchal inheritance

In this type of inheritance, multiple derived classes would be extended from a base class, it's similar to single-level inheritance but this time along with Samsung, Nokia is also taking part in inheritance.

Hierarchal inheritance

Hybrid inheritance

Single, Multilevel, & hierarchal inheritance all together construct a hybrid inheritance.

Hybrid inheritance

public class Mobile  
{  
       //Properties  
       //Methods  
}  
  
public class Samsumg : Mobile  
{  
       //Properties  
       //Methods  
}  
  
public class Nokia : Mobile  
{  
    //Properties  
   //Methods  
}  

Interface

Multiple inheritance where derived class will extend from multiple base classes.

Samsung will use the function of multiple Phones (Mobile & Telephone). This would create confusion for the compiler to understand which function to call when any event in mobile is triggered like Dial () where Dial is available in both the Phone i.e. - (Mobile & Telephone). To avoid this confusion C# came up with the concept of interface which is different from multiple inheritance.

If we take an interface it is similar to a class but without implementation & only declaration of properties, methods, delegates & events. The interface enforces the class to have a standard contract to provide all implementation to the interface members. Then what is the use of an interface when they do not have any implementation? The answer is, that they help have readymade contracts, only we need to implement functionality over this contract.

I mean to say, Dial would remain Dial in the case of Mobile or Telephone. It won't be fair if we give different names when the task is to Call the person.

The interface is defined with the keyword 'interface'.All properties & methods within the interface should be implemented if it is been used. That's the rule of interface.

Samsung

interface IMobile   
{   
    void Dial();   
}   

interface ITelephone   
{   
    void Dial();   
}   

public class Mobile : IMobile, ITelephone   
{   
    public void Dial()   
    {   
        Console.WriteLine("Dial a number");   
    }     
}  

Conclusion

Following the above principle and keeping in mind the four pillars of OOPS will lead you to develop a good program and connect it with the real world. I hope you like this article. Don't forget to share your comment whether it's good or bad. Sharing is valuable no matter what.

Download the file for the same code.

Reference


Similar Articles