DEV Community

Cover image for Object-Oriented Programming - The Bases
Flavio Rozendo
Flavio Rozendo

Posted on

Object-Oriented Programming - The Bases

Object Oriented Paradigm, or OOP, is a programming paradigm used on a large scale in the software industry. A lot of software we use is built in OOP, from social media to business applications.
This paradigm can be loved or hated, depends with who you are talking to. But no one can deny its importance. So, before understand more about OOP, let's talk a bit about programming paradigms.

Programming paradigm

A programming paradigm is a set of concepts and principles that define how we deal with and resolve problems. It refers to how a programming language organizes, stores, and manipulates data. Different paradigms may resolve the same problem using a different approach, but all of them can achieve the same objective.
The program paradigms might differ from each other in some aspects, such as the way code is organized, syntax, grammar, and even the way that the execution model works. They are the outcome of research and studies in computer science, incorporating widely used techniques from earlier practices.

The main programming paradigms currently are:

  • Object Oriented
  • Functional
  • Procedural
  • Imperative
  • Declarative

A programming language can implement more than one paradigm if they want to. For example, Java and Python work with more than one. However, some languages, such as Haskell, are binding to a specific one.

OOP History

Coming back to OOP, it’s difficult to determine a unique starting point. There were references to terms and techniques of OOP back in the 1950s and 1960s when groups of studies at MIT University already used terms as objects and instances. SIMULA is a programming language developed at that time and used some concepts used nowadays in OOP.
However, the first language considered OOP and used on a large scale was Smalltalk, with its first version launched in the 1970s. The real success of this paradigm only began between the end of the 1980s and the beginning of the 1990s. The launch of C++, a C language with support to OOP, was one of the triggers for this success.
Since then, OOP has been one of the most used paradigms in the world. A set of famous languages support it, such as Java, C#, Python, Javascript, Kotlin, and PHP.

How OOP Works?

OOP is based on objects. But what does this mean? To answer this question, it's common to say that objects represent things from the real world in software. Maybe this is not the best explanation so we will try a different one.
Let's get a bank account as an example. When we open an account, we have some informations about this account, such as agency, account number, and balance.
We also need to execute some operations, such as withdrawing, depositing money, paying bills, and receiving transfers from other persons.
So in the end, to represent an account, we need a set of data and behavior. And this is exactly what an object is. We can use our object to store the state, such as the account number and balance, and also define how we can manipulate our data and change this state.
In OOP, a computer program is nothing more than a collection of objects, and the software works from the interaction between those objects.
This paradigm has a lot of benefits, but in the end, the main objective is to make software that is easy to maintain, change, and grow. Before OOP, some software was too confusing to understand, making any change, even the small ones, very difficult. With objects, we group data that represent something and define the boundaries and rules for those data. With this, we achieve modularity, reusability, scalability, maintainability, and extensibility easier.

Basic Concepts

Now, let's go deeper into some technical concepts of OOP. Here I will use some code examples, based on Java language, but that could be adapted easily to any other language that supports OOP.

Classes

Classes, or concrete classes, can be defined as a template for objects. The goal is to create a reusable structure, defining fields and methods, that will be used to create as many objects as it needs. Here is an example of how to create a class:

public class CodeExample {
    int id;
    String name;

    public void save() {
       //more code
    } 
}
Enter fullscreen mode Exit fullscreen mode

In a class, fields are where our object data is stored. Those data also define the state of an object. A class can have as many fields as it wants, without limitations, although a large class is difficult to handle. Fields can also be known as properties or attributes.
Otherwise, methods are the behavior side of a class. Methods define how the data of an object can be manipulated, and how an object state can change. As fields, methods don't have any limitations. In some languages, methods are known as functions.
A class can be extended by another one. This means it inherits all fields and methods and can add its own. In those cases, the class inherited is known as superclass and the class that extends is known as subclass.

Interfaces

Interfaces are contracts that define a specific behavior, saying what a class must do without saying how it does it. In the interface, we create what is called method definition, where we set the method name, parameters, and return types, without the implementation.
Once a class implements the interface, it must implement all those methods, following the definition of the interface.
More than one class can implement the same interface. With this, objects of different types can have the same methods, even with a different behavior.
In OOP an interface can't have fields and implement methods, and each class can implement just one interface. However, some languages broke this rule, allowing methods implementation on the interface, and multiple interfaces per class.

public interface OopInterfaceExaple {
    public void someMethod(int parameter);

    public double anotherMethod();
}
Enter fullscreen mode Exit fullscreen mode

Abstract Classes

An abstract class is a mix between classes and interfaces.
This kind of class can define fields and methods as well. Besides that, as the interfaces, this class can create a method definition without creating the implementation. These methods are known as abstract methods.
Because of this behavior, we can't create an object from an abstract class.
To use an abstract class, we must extend this class with a concrete class. When we do that, as happens when a class implements an interface, we must define a concrete implementation for all the abstract methods.
We can have an abstract class extending another abstract class. However, we still can't create an object, even if the new abstract class implements all abstract methods.

public abstract class AbstractExample {
    public abstract int someAbstractMethod(); 

    public long someConcreteMethod(long a, long b) {
        return a + b; 
    }
}
Enter fullscreen mode Exit fullscreen mode

Objects

We already discussed what is an object in OOP. But now that we know classes and interfaces, let's talk more, focusing on the technical part.
Objects are primary components of the OOP paradigm. They are instances of a class, which means they are a self-representation of the class.
We can make a parallel between software and architecture. When an architect creates a project, it defines how a house should be built, without building anything. With the project, we can create as many houses as we want. All the houses will have the same base structure but have no relation and can be different in some aspects, such as inside and outside color.
Objects and classes work the same. A class defines the fields and methods that the objects will have. With a class, we can create as many objects as we want. Those objects share the same structure, so they all have the same fields and methods. However the state of each object is individual, and they don't share data between them.
We can use the command new to create a new instance of an object.

SomeClass object = new SomeClass();

AnotherClass anotherObject = new AnotherClass(value);
Enter fullscreen mode Exit fullscreen mode

Each object will be a set of fields and methods.

Fields

As we said more than once, a field keeps the object data and state. However not all the fields are the same, and they can hold different types of information. This can be different from language to language, but some types exist in almost all of them: int, float, double, char, and boolean.
Each type of field can hold a specific information. For example, int fields are for integer numbers, and boolean stores true or false.

Methods

Methods is where the action of an OOP application happens. Besides the possibility of changing the state of an object and manipulating their data, they also can call other objects, as long as they have an instance of this object they want to call.
A method can have parameters, which are values received when this method is called. There are no limits to how many parameters a method has, but the more they have, the harder it is to interact with them.
They can return a value as the result of its operation. Usually, a method can return only one type of value, but some languages allow the return of different types, and some more than one return at once.

someObject.makeSum(10, 5); 

someObject.printMessage("Hello OOP");
Enter fullscreen mode Exit fullscreen mode

More concepts

Besides classes and objects, there are other important concepts to know before the next step.

Constructors

Constructors are special methods called when the object is created. They are used with the new keyword and called only once in the object lifecycle.
We use this method to set up the object on its creation, ensuring its state before using it.
We can have parameters on constructors, and some languages allow a class to have more than one. When this happens, each version must distinct on the number of parameters, or they should have different types.

public class SomeClass() {

    public SomeClass() {
        //init object state
    }

    public SomeClass(int value) {
        //init object state
    }

    public SomeClass(String message) {
        //init object state
    }

    public SomeClass(int value, String message) {
        //init object state
    }
}
Enter fullscreen mode Exit fullscreen mode

Destructors

Destructors are also a special method but are the opposite of constructors. This method is called before the object is destroyed. As constructors, they are called automatically and only once on the object lifecycle.
With this method, we can perform cleanups and release resources used, such as memory, files, and network connections.
Not all languages implement this kind of method. Some languages work with garbage collectors to release resources instead of destructors.

Access Modifiers

Although the basics of any OOP application are the communication between objects, it's not desirable to allow full access to all methods and fields of any object. Sometimes we want to hide some fields and methods and allow access to only a set of objects, or even hide everything.
This behavior can be achieved with access modifiers. They can define the level of visibility of classes, methods, and fields. This way, we can control what we expose, how the state of an object can change, and who can change this state.
Again, this can be different from language to language, both in behavior and in existing types, but basically, there are four types of access modifiers:

  • public: there are no restrictions on access, fields or methods are accessible from anywhere.
  • private: allows access only inside the class where the method or field is defined, so they cannot be accessed directly from outside the class.
  • protected: members protected are accessible within the class in which they are defined and by subclasses.
  • default: some languages have default access if no modifier is provided, and the access is allowed just in the same package or something analog to this (namespace, assembly).
public class ExampleClass {

    private int someValue;

    public ExampleClass(int value) {
        int someValue = value;
    }

    protected int giveMeResult(int anotherValue) {
        return someValue + anotherValue;
    }
}
Enter fullscreen mode Exit fullscreen mode

Overloading

Sometimes we need to do the same thing in different ways. In OOP we can do this using a technique called overloading.
Overloading allows us to have more than one version of the same method. In this case, we consider the same when the method name and the return type are the same. In overloading, we must have different parameters, either type or quantity, for each version of the method.
For example, we can create a printNumber method that takes an int value and prints it on the screen. We can also have another version that takes a long value. It's also possible to have a version that receives an int and a long, sum them, and print on the screen. The only thing different between all versions is the parameter types.

public void printNumber(int value) {
   //print the number
}

public void printNumber(long longValue) {
   //print the number
}

public void printNumber(int value, long longValue) {
   long result = value + longValue;
   //print the number
}
Enter fullscreen mode Exit fullscreen mode

Overloading can be done in the same class, but a subclass can overload a superclass's method.

Override

Unlike overloading, override is when we change a method behavior, without changing the definition.
A subclass can override a superclass method, creating a method with the same name, parameters, and return type. This way, the subclass can change the behavior to its needs.
It's possible to completely override the method, or include his behavior, and then call the original method of the superclass, taking advantage of what exists there.

public class SuperExample {
    public void someMethod(long value) {
        //super class behavior
    }
}

public class SubExample extends SuperExample {
    @Override
    public void someMethod(long value) {
        //sub class behavior
    }
}

Enter fullscreen mode Exit fullscreen mode

These are some basic characteristics of OOP paradigms, and there was already a lot to talk about. However, we will save the best for another post: the main pillars of OOP.
See you soon! Thanks!

References:

Top comments (0)