Unlocking the Power of Object-Oriented Programming: A Journey Through the Principles !
Complete Guide to Object-Oriented Programming Principles.
What you will learn from this Article?
In this article, I will provide you with an insight into Object-Oriented Programming (OOP) through a detailed example. We will explore key concepts of OOP, including classes, objects, methods, and attributes. Additionally, I will explain the fundamental principles of OOP, namely encapsulation, polymorphism, abstraction, and inheritance, in detail.
Introduction to Object-Oriented Programming!
Before we delve into explaining the principles of Object-Oriented Programming (OOP), let's first understand its definition. In modular programming, such as using the C language, we can create variables to store integers, strings, characters, and other data types. However, when it comes to real-life objects, how do we incorporate them into our programs? This is where the concept of Object-Oriented Programming comes into play. OOP enables us to create objects, such as cars and humans, within our program. These objects possess attributes and methods that reflect their behaviour.
So, in conclusion, if you aspire to develop a car driving simulator game, you would start by creating a Car class that encompasses all the necessary information about a car. This class would serve as a blueprint for defining the properties and behaviors of cars in the game. By instantiating objects or instances of the Car class, you can customize each car by specifying its model, brand, color, and other attributes. Object-oriented programming (OOP) is not limited to game development; it finds applications in various domains such as finance, machine learning, mathematics, and more.
A Simple Example In C#!
By speaking about cars previously, let's create a simple class, and consider a scenario where we create a basic car with several attributes and methods in C# :
public class Car
{
private string brand;
private string model;
private int year;
private string color;
public Car(string brand, string model, int year, string color)
{
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
}
public void StartEngine()
{
Console.WriteLine("Starting the engine of the " + brand + " " + model);
}
public void Accelerate()
{
Console.WriteLine("Accelerating the " + brand + " " + model);
}
public void Brake()
{
Console.WriteLine("Applying brakes to the " + brand + " " + model);
}
public static void Main(string[] args)
{
Car myCar = new Car("Toyota", "Camry", 2022, "Silver");
myCar.StartEngine();
myCar.Accelerate();
myCar.Brake();
}
}
In the previous example, the Car class encapsulates various functionalities for managing a car, including starting the engine, accelerating, and braking. Additionally, it includes attributes such as the car's brand, model, year, and color. By instantiating the Car class within the main function, we created an object called myCar.
With this implementation, you have the flexibility to create multiple instances of the Car class, each representing a unique car with its distinct color, brand, and model. This allows you to easily customize and differentiate the cars in your program.
For example, you can create a red Toyota Camry, a blue Honda Civic, or even a black Ford Mustang. The possibilities are endless, and you can tailor each car object to match specific preferences or requirements.
This approach demonstrates the power of object-oriented programming, as it enables you to create and manipulate objects with distinct characteristics and behaviors. By leveraging the Car class, you can efficiently manage a wide range of cars within your program, providing flexibility and modularity in your codebase.
What are the Methods and Attributes in OOP?
A method defines the operation that an object can execute, it includes algorithms and instructions that define how an object will interact with its environment and other objects. For instance, methods like startEngine() and brake() enable us to do specific actions related to the car functionality.
Attributes represent the characteristics and attributes of an object. They hold the data associated to the object and its state, for instance, in our previous example, attributes like brand, model and color can store specific characteristics of each instance of the car that we create.
The 4 principles of OOP
Now, that you have an Idea of what OOP is, let us delve into its 4 principles which are encapsulation, abstraction, inheritance and polymorphism.
Encapsulation
Encapsulation means that the class that holds the state, decides the degree to which the methods and attributes will be accessed.
Encapsulation enables us to define the accessibility level for an element inside a class, these levels define the level of access to data.
There are 4 types of visibility :
By default visibility: When no access modifier is specified, the visibility of members (such as variables and methods) is determined by the default rules of the programming language or class. This may vary depending on the language and the specific situation. In C# for example, if no access modifier is specified, then the visibility is by default private.
Public visibility: This is the lowest level of visibility. Public members are accessible from outside the class. They can be accessed and used by other classes, objects, or modules.
Private visibility: Private members are only visible and accessible within the same class. They cannot be accessed or used by any other classes, objects, or modules. This provides a way to encapsulate and hide the internal implementation details of a class.
Protected visibility: Protected members are visible and accessible within the same class, as well as in the classes that inherit from it (subclasses or derived classes). This allows derived classes to access and use the protected members of the base class while still keeping them hidden from other classes outside the inheritance hierarchy.
Now, let's take a simple example in encapsulation where we define some members with different visibilities:
using System;
class Car
{
private string brand;
private string model;
private int year;
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public int Year
{
get { return year; }
set
{
if (value >= 1900 && value <= DateTime.Now.Year)
{
year = value;
}
else
{
Console.WriteLine("Invalid year!");
}
}
}
public void StartEngine()
{
Console.WriteLine("Engine started!");
}
public void StopEngine()
{
Console.WriteLine("Engine stopped!");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
myCar.Brand = "Toyota";
myCar.Model = "Camry";
myCar.Year = 2020;
Console.WriteLine($"Car: {myCar.Brand} {myCar.Model} {myCar.Year}");
myCar.StartEngine();
myCar.StopEngine();
}
}
Abstraction
Abstraction is the process of hiding implementation details from the client, creating a boundary between the program and its user. In object-oriented programming (OOP), abstraction involves concealing the specifics of method implementations using abstract classes or interfaces, commonly used in languages like C# and Java.
For instance, consider a phone as a real-world example of abstraction. When you want to start your phone, you simply press a button. You don't need to know the underlying process of how the phone turns on.
The main purpose of abstraction is to simplify the complexity of a system and provide a clear and intuitive interface for the client to interact with. By abstracting away implementation details, the client can focus on using the provided functionalities without being burdened by the intricacies of the underlying system.
using System;
// Abstract class
abstract class Animal
{
protected string species;
public Animal(string species)
{
this.species = species;
}
public abstract void MakeSound();
public void Sleep()
{
Console.WriteLine("The animal is sleeping.");
}
}
// Derived class
class Dog : Animal
{
public Dog() : base("Dog")
{
}
public override void MakeSound()
{
Console.WriteLine("Woof woof!");
}
}
class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog();
myDog.MakeSound(); // Output: Woof woof!
myDog.Sleep(); // Output: The animal is sleeping.
}
}
Inheritance
Inheritance is a mechanism through which you can extend a class by creating a child class that inherits all the public and protected members from the base class. Additionally, the child class can have its own members (attributes and methods). For example, a car can inherit from a class called vehicle, and the car class will inherit the same public and protected members from the vehicle class while also being able to have its own members.
Now, let's take an example to understand the inheritance:
using System;
class Vehicle
{
protected string brand;
protected string color;
public Vehicle(string brand, string color)
{
this.brand = brand;
this.color = color;
}
public void Start()
{
Console.WriteLine("The vehicle starts.");
}
public void Stop()
{
Console.WriteLine("The vehicle stops.");
}
}
class Car : Vehicle
{
private int numberOfDoors;
public Car(string brand, string color, int numberOfDoors) : base(brand, color)
{
this.numberOfDoors = numberOfDoors;
}
public void Accelerate()
{
Console.WriteLine("The car accelerates.");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Toyota", "Blue", 4);
myCar.Start(); // Output: The vehicle starts.
myCar.Accelerate(); // Output: The car accelerates.
myCar.Stop(); // Output: The vehicle stops.
}
}
Polymorphism
Polymorphism describes the situation in which something occurs in several different forms. It's the ability of an object to take many forms. This means any child class object can take any form of a class in its parent hierarchy and of course itself as well. What this actually means is that the child class object can be assigned to any class reference in its parent hierarchy and of course itself as well.
Now, let's take a simple example of polymorphism in C#. We will create a class called Shape
, which has a function called Draw()
. Then, the child classes will override the Draw()
function and modify its implementation as needed:
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.Draw(); // Output: Drawing a circle
shape2.Draw(); // Output: Drawing a square
}
}
๐ค Bonus!
Subscribe to my newsletter now and receive free courses, valuable tips, and cheat sheets in PDF format! Stay up-to-date with the latest news and trends in your field and gain access to exclusive content only available to subscribers. Join our community today and start learning for free!
๐ค Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Twitter
If you like this article! Don't miss the upcoming ones, follow me and subscribe to my newsletter to receive more!
See you soon :)