Coronavirus disease and OOP paradigm in Java
Purpose of this article
I was thinking about writing my first article about OOP paradigm in Java but what bothered me was the topic on which I would build examples. So as on March 11, 2020 World Health Organization (WHO) labeled coronavirus outbreak as pandemic I thought it would be an interesting experience to use this opportunity to understand both the OOP paradigm and the coronavirus disease. It is important to learn about both as first one is a step forward in your development career and second can help save lives or at least retain the spread of the virus. So the main purpose of this article is to explain OOP using examples about coronavirus.
P.S. Do not pay attention to unused warnings in examples
What is OOP?
As the definition states: “Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods)”. In simpler words this is an approach or method of thinking about everything in objects. You describe their features in fields and abilities in methods. In particular lets describe Coronavirus disease as an object with its features and abilities.
So Coronavirus disease can be described with the following features (these are the basic characteristics that are selected to keep examples simple):
- name : COVID-19 which stands for COronaVIrus Disease — 2019
- symptoms : cough, fever, tiredness, runny nose etc.
- mortality rate : The Who’s director general, Dr. Tedros Adhanom Ghebreyesus talked about 3.4 % but this is based on the officially reported cases. If we count all the mild cases that do not get to hospitals than the rate will be 1% or lower.
- Short description : Novel coronavirus disease or COVID-19 is new type of coronavirus that has not been identified previously.
So now we have described the disease (these features are also related to as state) but current description is incomplete as we haven’t told yet what it can do. As any virus this also can
- spread : The disease can spread from person to person through small droplets from the nose or mouth which are spread when a person with COVID-19 coughs or exhales.
- affect : There are 4 levels of infection. When disease starts the lining of the respiratory tree becomes injured, causing inflammation. This in turn irritates the nerves in the lining of the airway. Just a speck of dust can stimulate a cough (first level). But if this gets worse, it goes past just the lining of the airway and goes to the gas exchange units, which are at the end of the air passages. If they become infected they respond by pouring out inflammatory material into the air sacs that are at the bottom of our lungs. (second level). When air sacs become inflamed this causes an “outpouring of inflammatory material [fluid and inflammatory cells] into the lungs and we end up with pneumonia (third level). Lungs that become filled with inflammatory material are unable to get enough oxygen to the bloodstream, reducing the body’s ability to take on oxygen and get rid of carbon dioxide (fourth level). This is the main cause of death.
Now the simple description of COVID-19 is complete. Easy, right? We can describe our object programmatically as easy as we did verbally.
In the above picture you can see the code or the programmatic description of our object. It is a simple class that describes the object with its features and abilities.
The features are call class fields or attributes and abilities are called methods.
You may probably wonder what does those private or public keywords mean? Well you can find out in the next section :)
Encapsulation
As they say encapsulation describes the idea of bundling data and methods that work on that data within one unit. This concept is also often used to hide the internal representation, or state, of an object from the outside. This is called information hiding. The idea is quite simple : if you have one or more attributes that are not visible from the outside and you can bundle them with methods that provide read or write access to them, it means you can hide specific information and control your object’s internal state.
One implements information hiding mechanism by making attribute inaccessible from the outside and by providing accessor methods otherwise known as getters/setters for attributes that can be read or modified by other classes.
In our example let’s see which attributes can be modified by other classes.
- Symptoms : everyone can read this information and it can be updated, as further research can introduce new symptoms or negate some of them
- Disease name : everyone can read this information but it can not be changed
- Official mortality rate : everyone can read this information and it can be changed as every day there are new confirmed cases and new fatal cases. This number can both increase and decrease.
- Is found in people : everyone can read this information but it can not be changed. It can not magically become false :)
- Description : everyone can read this information and let’s assume it can not be changed for now as we used the simple description.
Now let’s apply this restrictions of access programmatically. Here is what we will get :
Now about the private and public keywords. These are called access modifiers. Java has 4 of them.
- Private : it is the most restrictive and commonly used access modifier. Any attribute or method that has private modifier can be accessed only within the same class. No child or subclasses or other classes can not access them (This refers to any class both in the same and different package). It is best practice to use this modifier with all attributes and internal methods that should not be called from outside.
- No modifier or package-private : whenever you are not providing any modifier for your attribute or method it can be accessed within the same class and all other classes in the same package. This is why it is sometimes referred to as package-private. This might be a bit confusing at the beginning but in your practice you will meet a lot of cases when you will need to implement a set of logic inside your package but also have an API that will be accessible from the outside of you package. Here is when package-private modifier will come in handy.
- Protected : attributes and methods with the access modifier protected can be accessed within your class, by all classes within the same package, and by all subclasses within the same or other packages. There are cases when you need to make an exception for attributes and some methods of superclass in a way that subclasses can access them directly. This is where you use protected modifier.
- Public : this is the least restrictive access modifier. Methods and attributes that use the public modifier can be accessed within your current class and by all other classes. This modifier is almost never a good idea for your attributes and you should think carefully before using it with methods.
Inheritance
Inheritance is a mechanism which enables one class to acquire properties of another class which means that chid class (the one that inherits) can reuse attributes or methods of super class (the one that is being inherited). There are 4 main types of inheritance :
- Singe : this is the most simple type. Here one class inherits attributes and methods of second class. (A -> B)
- Multiple : this is the case when one class can inherit attributes and methods of one or more classes (A -> C && B -> C)
- Multilevel : this is the case when one class can inherit attributes and methods of second class which was already inherited from another class (A -> B -> C)
- Hierarchical : this is the case when one or more classes inherit attributes and methods of the same class (A -> B && A -> C && A -> D)
- Hybrid : this is the combination of single and multiple types (A -> B && A -> C && B->D && C -> D)
In Java to achieve inheritance we use extends keyword for classes and implements for interfaces. As Java does not support multiple inheritance we use interfaces.
For example:
class A extends B
class A implements InterfaceB
Now let’s try to understand inheritance using COVID-19. We know that COVID-19 is caused by a virus which belongs to the large family of coronaviruses. These viruses cause mild to moderate upper-respiratory tract illnesses, like the common cold, in people. There are hundreds of them most of which circulate in animals. Sometimes they can jump to humans (this is called spillover event) and can cause disease. Till this day 7 coronaviruses are known to cause human disease: 4 of them are mild (viruses 229E, OC43, NL63 and HKU1), the other 3 can have more serious outcome (SARS (severe acute respiratory syndrome : 2002–2004), MERS (Middle East respiratory syndrome : 2012 — present) and COVID-19 (Coronavirus Disease 2019 : 2019 December — present)).
Can you spot the relation between these diseases? Right! All of them are coronavirus disease so they are in hierarchical relation with it. Programmatically we will have one base or super class and all other 7 classes (or diseases) will extend this class by which they will inherit its attributes and methods. The following images show our base class and derived ones.
Previous 2 pictures describe classes of severe and mild coronavirus diseases respectively. As you can see they implement 2 base methods that are common for all diseases. Now let’s see how our Covid19 class has changed.
We could have used interface instead of simple class. I suggest you try to do it by yourself as it will be a good practice for you.
There is one important keyword in Java that will help you implement inheritance : super. It is like this keyword but instead of current object it enables you to access fields and methods of super or base class. For example we can change one of our classes of mild disease to use super keyword to call spread() and affect() methods of base class.
This is just one simple example of usage of super keyword. I suggest you do some research and try to use this keyword in any possible situation.
Polymorphism
Polymorphism is a mechanism that enables us to do the same action in different ways. In other words in object oriented programming it is the capability of a method to act differently based on the object it is acting upon. There are 2 types of polymorphism :
- Static : this is the type of polymorphism that occurs in the same class by overloading methods. To overload a method you need to have 2 methods with same name but different signature (remember : return value is not part of method signature) which basically means with different sets of arguments. This type is sometimes referred to as compile time polymorphism as the utilizable method is decided during compilation process.
- Dynamic : this is the type of polymorphism that occurs when child class overrides method declared in super or base class. To override a method you should declare a method in child class that will have the same name and signature as in super class. In Java you can use @Override annotation to explicitly declare that you the annotated method is overrides base method. But it is not mandatory. Compiler will find it out anyways. This type is also referred to as runtime polymorphism as the utilizable method is decided at runtime.
Did you notice that we have already used polymorphism in our examples? Correct! We have used dynamic polymorphism by overriding spread and affect methods in child disease classes. Let’s bring an example of static polymorphism in Covid19 class. As you know disease can affect people differently. In our example we learned that there are 4 degrees of infection. We can separate them in 4 different methods that will depend on the level of severity. Here is how it will be done :
Abstraction
As the definition states : “Abstraction is the process by which data and programs are defined with a representation similar in form to its meaning (semantics) while hiding away the implementation details”. In simpler words imagine a situation where you have n number of different objects. Each object can be described using numerous detailed features but among those features there are some common ones. Remember the 7 coronavirus diseases described in inheritance section? Let’s try to represent them using abstraction. In order to do so let’s consider the information we have: we know that
- All 7 diseases are caused by viruses belonging to coronaviruses family
- All 7 diseases are found in people
- All 7 diseases share common cold symptoms
- 4 of them have mild effect
- 3 of them may have more serious outcome
- All 7 diseases differ in mortality rate
- All 7 diseases have different names
These are the features of diseases. Now the abilities:
- All 7 diseases have the ability to spread in different ways
- All 7 diseases have the ability to affect human body in different ways
Now that we know all the common information of the 7 coronavirus diseases we can abstract this idea programmatically.
In Java abstraction is achieved using abstract classes and abstract methods. To declare abstract class we use abstract keyword. This type of classes differ from normal classes by ability to have abstract methods. A method is called abstract when it does not have body and has abstract keyword in declaration. This type of methods can not be final as child classes should implement its body. Let’s add the abstract version of our CoronavirusDisease class.
Easy, right?
Adding this class enables us to abstract the idea of global coronavirus disease and concrete examples of it that are found in people. We can extend this class as easy as we did with normal CoronavirusDisease class.
Thank you for your time.
Hope you guys enjoyed this article and it served its purpose to rise awareness about COVID-19 and helped you to understand OOP principles.
You can find example project in the following GitHub repository : https://github.com/sedamov/COVID-19-and-OOP
#StayHome #SaveLives
Other Useful Resources to Learn Java Programming
The 2020 Java Developer RoadMap
10 Things Java Programmer Should Learn in 2020
10 Tools Every Java Developer Should Know
10 Reasons to Learn Java Programming languages
10 Frameworks Java and Web Developer should learn in 2020
10 Tips to become a better Java Developer in 2020
Top 5 Java Frameworks to Learn in 2020
10 Testing Libraries Every Java Developer Should Know