Object-Oriented Programming

Object-Oriented Programming, also called OOP, is a high-level programming model different from procedural and functional programming most developers learn and work it. This model of software programming focuses on data and objects rather than functions and logic.

To work with OOP, developers have to combine a group of related variables and their functions into a unit. This unit is the object. The practice is called data modelling. Data modelling in OOP is used to represent real-life objects with their properties and behaviours tied together. Manipulation is done on the objects themselves - their states and behaviours rather than the data and functions.
The first object-oriented programming language developed was called Simula. It was developed in the 1960's at the Norwegian Computing Center in Oslo and is generally accepted as the first language with general programming language features. Despite this, another language, Smalltalk, developed in the 1980s is considered the only true object-oriented language and it set the path which other object-oriented languages must follow.
Many modern programming languages like Python and JavaScript support object-oriented programming as well as procedural. Languages like Java are purely object oriented while languages like C++ are regarded as object-oriented languages as well as a programming language with object-oriented features. This is because it is less object-oriented than some other languages like Ruby.

Difference Between Object-Oriented and Procedural Programming

Procedural programming is the most common type of programming used in languages like JavaScript and Python. It is the most widely taught and the first style of programming most developers encounter.
The code for procedural follows a top-down approach of logical steps and algorithms. It separates data and procedures. These procedures are called functions, routines and subroutines.
Object-oriented programming on the other hand is a programming paradigm where computations are carried out on objects and data together. OOP makes use of classes to create new objects and instances.
One difference between OOP and procedural is that OOP uses principles like abstraction, inheritance, encapsulation and polymorphism, making it more secure than procedural.

Class

A class is a blueprint of an object. They are the building block of OOP. They represent all the categories of an object and define the methods attached to an object. An instance is a specific object created. A class describes an object.
When an object is created, we describe its action and properties with a class. Since objects are real-life simulations, there could be many instances of the same class.
Let's say we have a dog in our program. There are thousands of dogs in the world and of different breeds, sizes, color, weight and height. We would need to create a class called Dog. This class would be the blueprint of a dog, having the physical features of a dog and the methods associated with it. Our dog will be an instance of the class of Dog.
To create different instances of a dog, rather than re-writing from scratch, we will use the blueprint of Dog to create as many dog objects as we want.

Creating a class

Classes are usually created by using the keyword class followed by an initializer or constructor. In Java, the constructor is defined using the access modifier and it takes the name of the class but without a return type.
In Python, the keyword __init__ is the class constructor and it is called when we create an instance of a class.
Here's an example of a Dog class in Java and Python.

Java

public class Dog {
  private String name; 
  private String breed;
  public Dog (String name, String breed)
  {
    This.name = Sammy; //properties 
    This.breed = Labrador; //properties 
  }
  //The method 
  public void speak()
  {
    System.out.println("My dog is " + this.name + "and it is a " + this.breed)
  }
}

Python

class Dog(): #creating a class
  #CLASS OBJECT ATTRIBUTE
  species = "mammal"
  def __init__(self, breed, name):   #this is a method to initialize a class. self is important
    self.breed = breed   #properties
    self.name = name      #properties

myDog = Dog("labrador","Sammy") 
print(myDog.breed) #labrador 
print(myDog.name) #sammy 

Importance of Class

  • They provide a blueprint or template for creating objects
  • They support inheritance.
  • Code reusability

Instance, Methods and Properties

An instance is an individual or specific object created. An object, MyDog that belongs to a class Dog is an instance.
Methods in OOP are actions to be performed by an object. They are binded (binding is the association between a method and class) to specific classes and can be in-built or custom. In-built methods are methods pre-defined by the language like len in Python that calculates length. Custom methods are operations written by the developer to be performed on a class.
Methods are to OOP what functions are to procedural. They are reusable and can be inherited.
Properties are like variables. They are the description of an object. For example, a dog has size, color, weight, and height. These attributes are the properties of the dog.

Principles of OOP

OOP has four major fundamental concepts or principles. Understanding these principles and how they work is the first step to understanding OOP.

Inheritance

Inheritance is a concept that allows the creation of new classes from an existing one. The inherited class becomes a subclass or a child class of the parent or super class. There are several types of inheritance,

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Hybrid inheritance
  • Multi-level inheritance

When a class is inherited, it has all the same fields and methods of the super method in addition it's specific methods and functionalities. Inheritance makes a class DRY (Don't Repeat Yourself).
A practical example of inheritance is the relationship between a parent and it's parent. When a child is born, it inherits some genes from it's parent but it is also a distinct person with it's own unique traits.

Encapsulation

Also called data hiding is an important aspect of OOP. This concept puts restrictions within a class to keep the data and code tied together and safe within a single unit. With encapsulation, properties and methods cannot be easily accessed and this prevents accidental or non-approved modification of data.
A practical example of encapsulation is a company with different sections. A manager in the sales section does not have access to documents in the accounts section. To get the files there, the sales manager would have to request for access from the accounts section.
A class is an example of encapsulation. All of its methods, properties and variables are hidden within the class itself. Access modifiers - either public, private and protected, are required to determine the type of access to a code.

Abstraction

Abstraction is a concept that allows us to hide internal details from external influences. It is the representation of complex things in a simpler way.
In abstraction, the internal mechanisms of a program are hidden and any other implementation code. Only relevant details are revealed. It is used to create a boundary between the application and the user.
A practical example of abstraction is logging into a website. When you provide your name, email and password in a form, you are not privy to the nitty-gritty details of server and https protocols and how your details are authenticated. All you have is a login success or error message.

Polymorphism

Polymorphism is the ability of different objects to take on different forms in response to one code. Polymorphism models the real-life social environment where different persons could react in different ways to one action. It allows us to define one instance and have multiple implementations of it.

Access Modifiers

Access modifiers are keywords in OOP languages that set accessibility of classes, methods and other members. Access modifiers are used to implement encapsulation. The three major modifiers are public, private and protected. C++ and Python has these three, Java has four while C# extends the number to six. Every language has it's way of defining it's access modifiers.

PUBLIC ACCESS

This is the primary and default modifier. When a class is defined as public, it is accessible to every other class set as public and to classes of other access modifiers too. It has no scope restriction. If there's a need to debug a public class, the bug could be from anywhere and any package in the code.
A developer who doesn't want his code to be modified by just anyone but still wants other processes to read the data can make his code protected or private but set with a public function.
In Java, a public class is set by the public keyword with the constructor. In Python, all classes are public by default unless otherwise stated.

PROTECTED ACCESS

Protected methods can only be accessed by the class they are defined in and any other sub or inherited class. In Java, protected classes are defined with the protected keyword in the constructor.

class Dog { 
  // protected method 
  protected void display() { 
    System.out.println("This is a dog"); 
  } 
}

In Python, protected classes are defined by adding a single underscore (_) as prefix to the variables.

class Dog(): 
  def__init__(self, name, breed) 
    self._name = name 
    self._breed = breed

PRIVATE ACCESS

A private method is one that is available only to the class it is defined in. Private methods are usually the easiest to debug as bugs are contained only within the method. In Python, two underscores (__) are added as prefixes to the variables to make a method private.
In Java, interfaces and classes cannot be declared as private, only nested classes can.

Conclusion

Despite its very unique advantages - reusability, maintainability, faster development, high quality software and improved software development productivity, OOP has been criticised by some developers. They attack its steep learning curve, bloated code (due to misuse of inheritance) and shared mutable state.

Author

Ivan Georgiev | Software Engineer

Ivan is an extremely intelligent and knowledgeable professional with a hunger for improvement and continuous learning. Being versatile in a number of programming languages, he picks up on new tech in a matter of hours. He is a person that masters challenges by investigation and clear, structured execution, bringing in his experience and innovative ideas to solve problems quickly and efficiently. Ivan is also a Certified Shopware Engineer.