Object-Oriented Programming – OOP

Object-Oriented Programming – OOP

Hi there, welcome to my introduction to Object-Oriented Programming article. In this article you will learn about the amazing world of OOP programming. This article assumes that you have basic knowledge of Java, Kotlin or any other OOP programming language, such as PHP. Do not worry if you have no idea what the heck those are, as I will be explaining them from a beginners perspective.

Lets start by introducing what objects are, what they are and how to use them. We will not be building an app, but I will be explaining all the needed basics, using relevant code samples.

Object-Oriented Programming – OOP

Object-Oriented Programming – OOP is a type of programming driven by modelling your code around building units called objects. Each object represents an object in real life like a book, a building or a car.

Today, all modern programming languages are object oriented. The idea is, when you are coding, you want to solve a real life problem and modelling your code to match what you are trying to solve makes perfect sense.

For example, if you are building a pokemon game, your code would definitely have an object for each of the characters. Each object is responsible for holding the data that describes itself, for example a name, a number indicating the health level and so on. These are referred to as fields or attributes.

Object-Oriented Programming (OOP)

Apart from having fields, objects are also capable or performing actions. A pokemon for example can attack or dodge. These actions are known as methods.

Object-Oriented Programming (OOP)

Objects combine variables together to make your code meaningful. This makes your code easy to understand and more organized, which results to easy code maintainance. An object is an enhanced data type, a variable that you get to design.

Object-Oriented Programming (OOP)

Primitive variables only store a single item, but an Object Variables can store multiple items inside it, all in one single variable and it can also perform actions using methods. An object type is made up of many primitive types.

Object-Oriented Programming (OOP)

Fields

The fields of an object are all the data variables that make up that object. They are also sometimes referred to as attributes or member variables. These fields are usually made up of primitive types like integers or characters, but they can also be objects themselves. For example a book object may contain fields like titleauthor and numberOfPages. Then a library object may contain a field named books that will store all book objects in an array.

Accessing fields:

Accessing a field in an object is done using the dot modifier ‘.’  For example, if we had an object called book that contains these fields:

To access the title field you would use:

Methods

You might have also noticed that running actions in objects look very much like calling a function. That’s because that’s exactly what it is. Methods are functions that belong to a particular object. When we get to creating our own object types later in this article we will be creating methods the same way we used to created functions.

Calling a method

To use a method you call it (just like calling a function). Methods, just like any function can also take in arguments. For Example: Assume that our book object has a method called setBookmark that takes the page number as a parameter:

Summary

Fields and Methods together are what make an object useful, fields store the object’s data while methods perform actions to use or modify those data. However some objects might have no fields and are just made up of a bunch of methods that perform various actions. Other objects might only have fields that act as a way to organize storing data but not include any methods!

Constructors

Constructors are special types of methods that are responsible for creating and initializing an object of that class.

Creating a constructor is very much like creating a method, except that:

  1. Constructors don’t have any return types
  2. Constructors have the same name as the class itself

They can however take input parameters like a normal method, and you are allowed to create multiple constructors with different input parameters.

Here’s an example of a simple constructor for a class called Game

Default constructor

A Default constructor is one that doesn’t take any input parameters at all! It’s optional, which means if you don’t create a default constructor, it is assumed there’s one by default that doesn’t really do anything. However, if the class has fields that need to be initialized before the object can be used, then you should create one that does so.

For example, assume we have a class Game that has an integer member field score, we’d like to make sure that any object of type Game will start with the score value set to 0. To do so, we need to create a default constructor that will initialize the mScore field

Parameterized constructor

As we’ve mentioned earlier, a constructor can also take input parameters. Let’s assume that some games start with a positive score value and not just 0, that means we need another constructor that takes an integer parameter as an input, and uses that to initialize the score variable.

Accessing a constructor

Unlike normal methods, constructors cannot be called using the dot . modifier, instead, every time you create an object variable of a class type the appropriate constructor is called. Let’s see how:

The new keyword

To create an object of a certain class, you will need to use the new keyword followed by the constructor you want to use, for example:

This will create an object called tetris using the default constructor (i.e. tetris will have an initial score value of 0)

To create a game that is initialized with a different starting score you can use the second constructor:

If you do not initialize an object using the new keyword then its value will be set to something called nullnull simply refers to an empty (uninitialized) object. null objects have no fields or methods, and if you try to access a null object’s field or call its method you will get a runtime error.

In some cases, you might want to explicitly set an object to null to indicate that such object is invalid or yet to be set. You can do so using the assignment operation:

Access Modifiers

We all make mistakes, and some mistakes in a program can result to catastrophic failures. Using the correct access modifiers prevents us from making mistakes in our code. You can label a field either private or public. Making it public means other classes can access it, while private makes it hidden from rest of your program but is accessible and usable inside the class that created it.

However, it’s strongly recommended in Java to label ALL fields as private:

For example , when defining a Book class, we would define everything as private, and only initialize them in the constructor:

This way you can guarantee that once a book object has been created, the title and author will never change!

Let us now look at some core principles of OOP

Encapsulation

This means that each class is just like a capsule that contains everything it needs and nothing more. Encapsulation can be used to hide data members and members function. Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition. Typically, only the object’s own methods can directly inspect or manipulate its fields. Below is an example in Java:

Inheritance

This refers to passing down of traits or characteristics from a parent to their child, as it the case in real life. Classes extend other classes and uses the extend keyword:

Take for example these 3 classes which have similar fields, which are same across them:

We could extract the common fields to a different class and extend the class to the children easily by doing this:

Polymorphism

This is the condition of occurring in several different forms. This happens when a class extends another class. Let us look at the following example:

Imagine a class called Person

We have two more classes, that extend the Person class, with additional fields or attributes, as shown below:

We you want to create a Student or a Teacher object, you can create them individually and also initialize them using their respective constructors as shown below:

So far so good. But remember, both Student and Teacher are extending the class Person. This means they are of type person by default. You can declare them both as type Person and initialize them using their own default constructors.

This flexibility allows you to treat children objects as if they were the types of their parents and still use all the functionality inside the child class itself. We will explore this in details when we will start working on Android Apps from scratch using Kotlin.’

Conclusion

Well done! I hope you have learnt a lot of things from this article. Congratulations, now you are familiar with most of the important concepts of Object-Orieinted Programming – OOP. We are going to start applying these concepts soon. Remember to leave questions or suggestions below, and I will be glad to get back to you. I hope you really enjoyed this article, and see you soon 🙂

I would like to appreciate the efforts of my great friend and collegue Henry Mbugua, a Python Guru and a Web Developer, who took the time to go through this article and recommend major changes. You can follow his articles here, if you would like to learn some cool python stuff!

Happy Coding!

More From Android Study:

4 Replies to “Object-Oriented Programming – OOP”

  1. I think i get some concept right..thanks buddy hope java will come easy for me i want to make some crazy apps that have always dreamnt of…making ideas come alive

    1. Understanding OOP is key to learning Java, the journey should become a bit easy now. Developing apps on the other hand is an amazing experience, that you will come to love.
      Cheers and Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *