Hey everyone! This article will give you a sound understanding about OOPs concept in Java. But even if you’re from another programming background such as C++ or Python, you can utilize this article to gain a thorough understanding about OOP principles. Examples provided in this blog are Java language based. Nevertheless the explanations can be applied to any object oriented programming language as these basic pillars are language independent, even though the implementations can be different from language to language. Before diving into OOPs concepts, I will give you a small insight about different ways of writing code including OOP.
There are basically 3 programming paradigms which you can follow when writing code. They are,
- Procedural Programming.
- Functional Programming.
- Object Oriented Programming.
Procedural Programming / Inline programming.
This way of programming consists of data and procedures that act upon the data. Procedures simply consist of a series of computational steps to be carried on. During the execution of the program any of the procedures can be called out. And thus instructions within them will be executed step by step.
Languages such as C and Pascal use this concept of Procedural Programming.
The basic idea behind functional programming is coming up with a set of functions (or methods in some circles) to get things done. These functions have code blocks injected to them and will serve a specific purpose.
Languages such as Scala and Erlang use this paradigm.
Object Oriented Programming.
This concept deals with classes and objects. In this way code chunks are within classes. Classes can be simply called as blueprints which can be used when creating objects. Object is an instance of a class. Classes can contain member variables and methods. Variables describe the state of the class whereas methods describe the behaviour of the class.
There are so many advantages of coding in this paradigm. Few of them are,
- Modularity for easier troubleshooting — When you use OOP when coding you know exactly where to look when something goes wrong. You don’t have to muck through the entire code just to find that one line which caused the bug. This will save you a lot of time in the long run.
- You can reuse your code through the inheritance concept. (Don’t worry you will know what inheritance is in a few minutes)
- OOP principles open up the doors to effective problem solving — Object oriented programming is the most natural and pragmatic approach you can take to solve a problem. But it needs your practice and patience in the beginning. Once you get the hang of it , voilà you’re ready to write clean code.
Firstly, we should get a quick glance about what classes and objects really means. Please take a look around the place you’re sitting right now. You might see a table, chair, a water bottle or a cell phone in the process. These are all real world objects. Let’s take the water bottle as an example.The person who made it should have a mould to manufacture the bottle that you have now. It’s the same with OOP too. Classes are the blueprints (or the mould in our example) to make objects (water bottles).
Classes have a state and behaviours. As it is mentioned earlier Member variables describe the state of the class. Member methods describe the behaviour of the class. And without objects, classes are of no use. We have to create objects or instances of the class to get the real use of it. I’m gonna explain this with an example.
As you can see this Car class has member variables which describe the state of the car. And the following image will show you how methods are used to set and get values to each one of the variables. Note that all variables have been declared as private.
Then we can create instances of this Car class in the Main class.
You can use this Porsche object to set values to the variables in Car class as well as to retrieve those values from the Main class since the variables have been declared private (This is also a OOP principle and you’ll see later in the article).
Now that you got a gist about what object oriented programming is and behaviour of classes and objects you can easily go through the rest of the article and understand about the four basic pillars of it.
It’s time to investigate the skeleton of Object Oriented Programming. Once you get a good understanding about these four concepts you can apply them to any object oriented programming language you wish. Just the way implementing these core concepts will be different from language to language.
To begin with, there are four pillars to object oriented programming in java. They are,
There are two main keywords that you will come across a lot when talking about inheritance. So it’s better to know what they are first.
Super class — Super class is simply the parent class which inherits its features down to the child classes.
Sub class — The class which derives features from another class is called the sub class.
Let’s dig in with an example. Imagine you’re going to make a calculator. But at first you include only a method to add two numbers.
In the future you may want to extend the functionality of this calculator to calculate the difference between two numbers on top of adding them. In this scenario you don’t have to write another class with adding two numbers functionality. You can just inherit that functionality and add any modifications you want, thanks to this concept in OOP.
This is just a very basic example on how to use inheritance concept but in reality this is a far more broad topic.
As long as java is concerned there are three types of inheritance supported.
- Single level inheritance — This is a single step relationship in which subclass inherits from the super class. This is a type of parent- child inheritance. The above practical scenario is an example for this kind of inheritance.
- Multi level inheritance — When a class extends a class which extends another class then it is called as multi level inheritance. This is a type of grandparent -> parent -> child inheritance.
3. Hierarchical Inheritance — In this case, one superclass serves as the base class to more than one subclasses.
When you execute the code, you’ll get the following result.
The biggest advantage of using inheritance concept is that it increases code reusability. Code which is already written in the base class does not need to be repeated again in subclasses. Note that opposite of this which is multiple inheritance is not supported in java by normal means. It can only be alternatively achieved through interfaces.
Polymorphism is simply “many” “behaviours”. This means single action, many behaviours. This can take place when many classes are related to each other by inheritance concept. Polymorphism can make these methods perform various tasks. Consider the following example.
This will give you the following output:
You can see in the above example how parent class reference is being used in making child class objects. This is a basic occurrence of polymorphism. In this example, multiple child classes have inherited a single base class.
There are two types of polymorphisms in java. They are,
- Compile time polymorphism/ Static binding — Method overloading in java is an example for this. Method overloading allows more than one methods to take the same name as long as their parameters are different in number, sequence or by the data type.
2. Runtime polymorphism / Dynamic binding — This is also known as Dynamic method dispatch. Method overriding in java is an example for this.
Which outputs the following:
In java, we can achieve abstraction using interfaces and abstract classes. You might be wondering what abstraction, interfaces and abstract classes means. Simply, abstraction is the process of hiding implementation while providing functionality to the user. Imagine you’re using an ATM to withdraw money. You can’t see all the logic and the codes of the program when you’re trying to do so. You’re just interacting with a nice user interface during the process to get your transaction done.
To create an abstract class, you have to use an “abstract” keyword when you’re declaring the class.
This abstract class can have abstract methods as well as non-abstract methods in it. But if a class has at least one abstract method, it must be declared as an abstract class. Also abstract methods do not have a body. The body is stuffed while inheriting in subclasses. Furthermore, you cannot create instances from abstract classes.
Another way of achieving abstraction is through interfaces. Interface is a reference type in java which is very similar to a class. Interfaces can only contain abstract methods.
Best way to visualise this is the medical capsule you use for your sicknesses.
Think of encapsulation as wrapping data (variables) and code acting upon the data (methods) into a single unit. The above capsule has different types of medicines blended together and placed in the nice coating. This is the same with OOP encapsulation as well. Problem is how are we going to achieve this target?
Well, we can fully encapsulate java classes by making data members / variables of the class private. Then we can generate getters and setters to make the class read-only. This is a method for data hiding as through this approach you have full control over the classes you write because other classes cannot access your member variables.
Also, it’s easy to carry on the testing process when your classes are fully encapsulated. This way of encapsulating makes unit testing a less nightmare. This way of encapsulating makes your application more secure, easy to maintain and less chaotic.
I hope you got a clear understanding about OOP concepts from this article. Practice more and more of it by applying it to your work. Cheers!