Object oriented programming tutorial | 4 basics OOPs concepts

In this article, we are going to talk about object-oriented programming and its 4 basics OOPs concept in C#.

Object Oriented Programming OOps
4 basics OOPs Concept in C#

What is object oriented programming?

Object-oriented programming (OOP) refers to a programming language that uses classes and objects in code, which have certain properties, methods, fields, and events.

OOP is used to structure a software program into simple, smaller, and reusable pieces of code (generally called classes), which are used to create individual instances of objects.

In simple words, we can say that any programming paradigm where data or everything is represented as an object is known as a pure object-oriented programming language.
OOps allows us to develop modular programs and assemble them as software applications. It allows data hiding, reusability, and extensibility of code.

In Object-Oriented Programming (OOPs), the programs are organized around classes, objects, and data rather than action and logic.

There are many object-oriented programming languages including C#, C++, Java, Python, and Ruby, etc.

What is a class in C#?

A  class  in C# is a user defined data type which has data members and member functions. It is a kind of placeholder or container that allows us to declare variables of different data types and methods to perform some operation.

In simple words, we can say that a class in C# is a template or prototype to represent a group of objects which share some common properties and behaviors.

A class is a blueprint or prototype for creating more specific, concrete objects.
In C#, each object can have unique values to the properties defined in the class.

Class is a reference type, It is a collection of objects.

Create a class in C#

We can use the class keyword, to create a class followed by the class name and the body enclosed by a pair of curly braces {}.

// class
public class Car
    {    
      // Data  members of a class
        public string brand = "Hyundai";
        public string modal = "Creta";
        public string color = "Red";
        public int topSpeed = 165;

        public void CarDetails()
        {
            Console.WriteLine($"Brand:{brand} Modal:{modal} Color: {color}: Speed:{topSpeed}");
        }
    }

What is an object in C#?

An object is an instance of a class that can be created by using the new operator in C#. An object is used to access defined variables, properties, functions, and other data members of a class.

An object can’t be created until or unless a class is instantiated. When an object performs some activities, It defines the object’s behavior.

So finally, a class is a template or blueprint for an object, and an object is an instance of a class that can inherit all the variables, properties, and methods from the class to perform certain actions.

Following are the characteristics of an object.

    • State: Represents data (value) of an object. It also reflects the properties of an object.
    • Behavior: represents the methods or behavior (functionality) of an object such as Drive, Brake, Speed, etc. of a car object.
    • Identity: It gives a unique name or ID to an object and enables one object to interact with the other object.
      The object ID is not visible to the external user. But, it is can be used internally by the compiler to identify each and every object uniquely.

Create an Object in C#

An object is created from a class using the new operator. As we have already created the class named “Car” in the above example, so now we can use this to create objects.

To create an object of the Car class, we have to specify the class name, followed by the object name, and use the new operator as below.

Create an object called “carObj” and use it to call the “CarDetails” method to print the details of the car.

using System;

namespace ClassExample
{
    // Car class
    public class Car
    {    
        // Data members
        public string brand = "Hyundai";
        public string modal = "Creta";
        public string color = "Red";
        public int topSpeed = 165;

        public void CarDetails()
        {
            Console.WriteLine($"Brand:{brand} Modal:{modal} Color: {color}: Speed:{topSpeed}");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            // Creating object of the Car class
            Car carObj = new Car();
            Console.WriteLine("****Print Car Details****");
            carObj.CarDetails();

        }
    }
}

Once we execute the above program, we will get the following result.

object in C# result
output of the above program.

What are the 4 basics of OOPs?

There are 4 major pillars or principles that makes a language Object Oriented.

    • Inheritance
    • Encapsulation
    • Abstraction
    • Polymorphism

What is Inheritance?

Inheritance is a kind of relationship or association between two classes that allows the object of the derived class to acquires all the properties and behaviors of a parent class object.

Inheritance means a parent-child relationship where we can create a new class by using the existing class code.

Parent Class: In Inheritance, the class whose features are inherited is known as parent class(or a generalized class, superclass, or base class).

Child Class: The class that inherits the existing class is known as child class(or a specialized class, derived class, extended class, or subclass).

Types of Inheritance in C#

    • Single Inheritance
    • Multilevel Inheritance
    • Multiple Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance

To know more about Inheritance please visit my previous article Inheritance in C# with examples.

What is encapsulation in OOPs?

Encapsulation is a technique to hide the properties and behaviors of an object to prevent the data from unwanted access by binding the code and data in a single unit called an object.

In C#, data inside an object can’t be accessed by any other object within a program, unless or until it is permitted to access.

if any object is maintaining or storing internal data safety this is also called data hiding. We can achieve it by using the private access modifier.

So, whenever we want any property of an object( constants, variables, fields, method) to be revealed or exposed to others, we just have to set it as public property and when we don’t want it to be, we mark it as private.

Encapsulation means hiding and binding of the data.

Encapsulation is the process of hiding of data implementation by restricting access to public methods or properties. Instance variables are kept private and properties or methods are made public to achieve this.

For example, we are hiding the empId and name fields of the Employee class in the below code snippet.
Encapsulation — private instance variable and public accessor methods or properties.

public class Employee
    {
        //private fields
        private int empId;
        private string name;

        // public properties to get or set private field (empId) value.
        public int Id
        {
            get { return empId; }
            set { empId = value; }
        }
        // public properties to get or set private field (name) value.
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

Accessing the private variables by using public properties or methods of a class is a good example of encapsulation.

Data Abstraction

Abstraction refers to the process of exposing only the relevant and essential data to the user without showing unnecessary information. The functional or operational part of any application is an abstraction.

Abstraction is the ability to show only relevant information of a class to the user without exposing the implementation details.

Abstraction in C# can be achieved by using the interface or abstract classes. Abstraction is done when we only wanted to inherit from a certain class but don’t wanted to create objects of that class. The abstract class holds the methods or the properties signature only, but the actual implementation of those methods or properties is made in the derived class.

Let’s see in the following example.

using System;

namespace AbstractionExample
{

    // abstract class
    public abstract class Employee
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        // abstract method
        public abstract double CalculateSalary(int hoursWorked);
    }

    // derived class
    public class FullTimeEmployee : Employee
    { 
        //implementation of the abstract class method
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 60.00 + 3500;
        }
    }

    // derived class
    public class PartTimeEmployee : Employee
    {
        //implementation of the abstract class method
        public override double CalculateSalary(int hoursWorked)
        {
            return hoursWorked * 65.00;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Creating object of the derived classes by using base class reference variable.
            Employee employee = new FullTimeEmployee();
           Console.WriteLine($"Full Time Employee Salary: $ { employee.CalculateSalary(40)}");
            employee = new PartTimeEmployee();
           Console.WriteLine($"Part Time Employee Salary: $ { employee.CalculateSalary(40)}");

        }
    }
}

Once we run the above program, we will get the following result.

abstraction result-OOps
Result of the above abstraction program.

In the above example, we have created objects of the FullTimeEmployee and PartTimeEmployee class, but we don’t create objects of the base class Employee. We only declare a variable of the abstract class called Employee to access the methods of the derived classes.

Polymorphism

Polymorphism: Polymorphism means when a method acts differently under different conditions by taking different types of parameters. In simple words, we can say that the multiple behaviors of a single object are called polymorphism.

Types of polymorphism in OOPs

Polymorphism in C# are mainly of 2 types:

    • Compile-time polymorphism (also known as Static polymorphism, Overloading, or Early binding)
    • Run time polymorphism (also known as Dynamic polymorphism, Overriding or late binding)

Static Polymorphism

The process of linking a method with an object during compile time is called early binding or static binding. C# provides the following two techniques to implement static polymorphism.

    • Method overloading
    • Operator overloading

Method overloading: Methods with the same name but different signatures. We can achieve method overloading by implementing multiple prototypes of the same method.

Let’s look into the following example of the method overloading for clear understanding.

In the following example, a class “Calculator” has two methods with the same name “Add” but with different input parameters (the first method has two parameters and the second method has three input parameters).

using System;

namespace MethodOverloadingExample
{
    // class
    public class Calculator
    {
        // Overloaded method: Method with the same name but  different signatures
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }
    }

     class Program
    {
        static void Main(string[] args)
        {
            // Creating object of Calculator class.
            Calculator calculator = new Calculator();

            // Here compile will know which methods need to call at the compile-time based on 
           //the signature of the method.

            Console.WriteLine(calculator.Add(10, 20));
            Console.WriteLine(calculator.Add(10, 20,30));

        }
    }
}

//Output:
//30
//60


Dynamic Polymorphism

Dynamic polymorphism or Run time polymorphism provides a mechanism to redefine or extend the functionality of a base class method in the derived class by using the override keyword.

Dynamic polymorphism gives us the provision to invoke all the identical or override methods of the derived class through the reference variable of the base class at the run time. To achieve dynamic polymorphism the base class method must be virtual or abstract and the derived class should have an override method.

Runtime polymorphism uses method overriding. In method overriding the base and child class can have method with the same name and signature, but a child class can provide a different implementation than its parent class using the override keyword.

Polymorphism in C# is extensively used in implementing inheritance.

Let’s create a simple program to understand the method overriding in C#.

using System;

namespace MethodOverridingExample
{   // Base class
    public class Animal
    { // virtual method
        public virtual void Eat()
        {
            Console.WriteLine("Eating food.");
        }
    }
    // Derived class
    public class Cow : Animal
    {   //override method
        public override void Eat()
        {
            Console.WriteLine("Cow is eating grass");
        }
    }
    // Derived class
    public class Lion : Animal
    {   //override method
        public override void Eat()
        {
            Console.WriteLine("Lion is eating meat");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Calling object of cow class via base class reference variable.
            Animal animal = new Cow();
            animal.Eat();
            // Calling object of lion class via base class reference variable.
            animal = new Lion();
            animal.Eat();
        }
    }
}

//Output:
// Cow is eating grass
// Lion is eating meat


Operator Overloading in C#: The process of making an operator perform different behaviors in different class instances is known as operator overloading.

Summary:

In this article, we learned about object-oriented programming in C# with examples. Also, we learned the 4 basics OOPs concepts in C# such as Inheritance, Polymorphism, Abstraction, and Encapsulation. I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Thanks for visiting.

Leave a Reply