Do you know four basics of Object Oriented Programming ?

Nadeeshani Welgama
9 min readJul 7, 2021

Object ? What is the object ? That is the first question when we start to talk about object oriented programming. Object is a entity that exist in the real world such as a book, pen, paper, chair, table, etc. Object oriented programming is a paradigm as well as methodology to design a program using classes and objects. The core purpose of the object oriented programming is to increase the maintainability and flexibility of programs. OOP brings together data and methods which behavior of it, in a object which means single location makes it simply to understand how program works.

OOP concepts in Java

There are four core OOP concepts in java name,

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Lets see above concepts briefly one by one.

Abstraction

Abstraction is hiding internal details and showing functionality is known as abstraction. In here only show the relevant data and hide the unnecessary details of an object from the user. Using simple things to represent complexity. The core purpose of abstraction is hiding the unnecessary details from the user.

As real world examples,

We all know how to turn the TV on, but we don't need to know how it works.

In phone call we don’t know the internal processing.

When you login to your fakebook account, you enter user_id and password and then login to the system, but we don’t know what happen when you press login, how the input data sent to server, how it verified.

A van in itself is a well defined object, which is composed of several other smaller objects like a steering mechanism, engine, gearing system, which are again have their own subsystems. But for humans, van is a single object, which can be managed by the help of its subsystems. Inner details are unknown.

Advantages of Abstraction :

Avoid duplication of code

Increase reusability

Reduces complexity

Increase security

Increase confidentiality

Eases the burden of maintenance

What is abstract class and abstract method?

An abstract class is a class that is declared with abstract keyword. It is a type of class in OOPs, that declare one or more abstract method.

Abstract method is a method that is declared without implementation. It is a method that has just the method definition. A method without a body is known as an Abstract method. This mostly declared where two or more subclasses are also doing he same thing in different ways through different implementation.

Abstract method must be declared in abstract class. An abstract class may or may not have all abstract methods, some of them can be concrete methods. Any class that contains one or more abstract methods must also be declared with abstract keyword.

Java program of abstraction using abstraction class

The classes in below program implement the shape interfaces.

abstract class TwoShape {
private double length;
private double width;
private double radius;

public TwoShape(double length, double width) {
this.length = length;
this.width = width;
this.width = radius;
}
// Declaring abstract method
public abstract void draw();
// Defining concrete method
public double getArea() {
return length*width;
}
}

public class Rectangle extends TwoShape {
public Rectangle(double length, double width) {
super(length,width);
}
public void draw() {
System.out.println("Drawing Rectangle");
}
public static void main (String args[]) {
// TwoShape object referring to rectangle.
TwoShape rect = new Rectangle(10,10);
rect.draw();
System.out.println("Area of given rectangle = "+rect.getArea());
}
}

Output:

Drawing Rectangle
Area of given rectangle = 100.0

Encapsulation

Encapsulation refers to he bundling of data(attributes), along with the methods(functions and procedures)that operate on that data, into a single unit. It does this so that the data is protected. It hiding information details and protecting data and behavior of the object. Encapsulate class is easy to test, therefore it is also better for unit testing. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. It is data hiding. When consider above image capsule, it encapsulates several combinations of medicine. It combination of medicine are variables and methods then the capsule will act as a class and the whole process is called encapsulation.

The core idea of this process is, if you have an attribute that is not visible from the outside of an object, and bundle it with methods that provide read or write access to it, then you can hide specific information and control access to the internal state of the object.

To achieve encapsulation in java need to provide public setter and getter methods to modify and view the variables values. And declare the variables of a class as private.

As the names indicate, getter method is retrieves an attribute and a setter method change it. According to the method you can decide if an attribute can be read and changed, read only or not visible at all. If the field is declared private in the class then it cannot be accessed by anyone from outside the class and hides fields within the class.

As real world examples,

When log into the Gmail account, there is a more internal processing taking place in the backend and user have no control over it. When user enter the password to logging they are retrieved in an encrypted from and verified and then user given access to the account. User do not have control over it that how the password has been verified. It keeps account secure to violate the misused.

Suppose you go to an automatic cola vending machine and request for a coca cola. Here automatic cola vending machine is a class. It contains both cola and service mechanism and they are wrapped under a single unit cola vending machine. This is called encapsulation. You cannot access the details about internal data like how much cans it contains, mechanism. This is data hiding.

Washing machine and it’s power button. When we switches the machine on then it works. But we did not know inside mechanism. The object is wrapped and inner details are hidden.

Advantages of Encapsulation :

Reduce human errors

Simplifies the maintenance of the application

Make application easier to understand

Protects an object from unwanted access by clients

Allow access to a level without revealing the complex details below that level

Code changes can be made independently

Increases usability

Encapsulation makes programming flexible. That mean user can edit and update code according to new specification.

Created read-only and write-only classes

Example code for Encapsulation :

For example when I created the Employee class. The attributes name, id number and age store the current store of the Employee object.

public class Employee {
private String name;
private String idNo;
private int age;

public int getAge() {
return age;
}

public String getName() {
return name;
}

public String getIdNo() {
return idNo;
}

public void setAge( int newAge) {
age = newAge;
}

public void setName(String newName) {
name = newName;
}

public void setIdNum( String newId) {
idNo = newId;
}
}
public class RunEncap {

public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("Jany");
encap.setAge(25);
encap.setIdNum("0909js");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
}
}

Output :

Name : Jany Age : 25

Inheritance

Inheritance is a mechanism to derive a class from another class for a hierarchy of classes that share a set of attributes and methods. Each class can only be derived from one another class called super class or parent class. The derived class is called sub class or child class. In inheritance can reuse the fields and methods of existing class. It related to classes and their hierarchy. Inheritance is the capability of one class to inherit capabilities or properties from another class in Java.

The parent-child relationship between classes can be represented in a hierarchical view often called class tree view. You use the keyword extends to identify the class that subclass extends. If don’t declare a superclass, your class implicitly extends the class object. Object is the root of all hierarchy (inheritance).

There are various types of inheritance in Java.

Single inheritance- One class extends another class

Multiple Inheritance- One class extending more than one class.

Multilevel Inheritance- One class can inherit from a derived class. Derived class becomes the base class for the new class.

Hierarchical Inheritance- One class is inherited by many sub classes.

Hybrid Inheritance- Combination of single and multiple inheritance.

As real world examples,

A child inherits the traits of his/her parents.

Human has ability to speak, breathe, eat, drink, etc.

The class ‘Car’ inherits its properties from the class ‘Automobiles’ which inherits some of its properties from another class ‘Vehicles’.

Advantages of Inheritance:

Application take less memory

Application development time is less

Application execution time is less

Application performance is enhance

Redundancy of the code is reduced or minimized therefore that we get consistence results and less storage cost.

Minimize the length of duplicate code in an application by putting the common code in the superclass and sharing amongst several subclasses.

Application code more flexible to change because a class that inherits from the superclass, can be used interchangeably.

Example code for Inheritance :

package inheritance; 
public class BaseClass
{
void features()
{
System.out.println("Feature A");
System.out.println("Feature B");
}
}
public class DerivedClass extends BaseClass
{
void ownFeature()
{
System.out.println("Feature C");
}
}
public class InheritanceTest
{
public static void main(String[] args)
{
// Create an object of the derived class.
DerivedClass d = new DerivedClass();

// Call features() method from the derived class using object reference variable d.
d.features(); // Call ownFeature() method using reference variable d.
d.ownFeature();
}
}

Output

Feature A             
Feature B
Feature C

Polymorphism

The word “poly” means many and “morphs” means forms. Polymorphism means having many forms. Polymorphism allows to perform a single action in different ways. In OOP occurs when a parent class reference is used to refer to a child class object. The concept that different classes can be used with the same interface. Each of these classes can provide its own implementation of the interface.

There having two types of polymorphism.

  1. Compile-time polymorphism/ static polymorphism- Achieved by functional overloading or operator overloading. If you can implement multiple methods within the same class that use the same name but a different set of parameters. That is called method overloading. Compile time can take a different form during compilation. Static polymorphism executes faster than run-time polymorphism at the compile time.
  2. Runtime polymorphism/Dynamic polymorphism- It is a process in which a function call to the overridden method is resolved at runtime. this is achieved by method overriding. This type of polymorphism doesn’t allow the complier to determine the executed method. The JVM needs to do that at runtime. Runtime can take a different form while the application is running. In overriding more than one method has the same name, number and type of parameters. Dynamic polymorphism executes slower than compile time polymorphism at the run time.

As real world examples,

A person at the same time can have different characteristics. Like a man at the same time is an employer, a father, a husband.

A cursor may take different forms like an arrow, a line, cross, or other shapes depending on the behavior of the user or the program mode.

You have a smartphone for communication. The communication mode you choose could be anything. It can be a call, text message, mail, camera, etc. The core purpose is common that is communication., but their approach is different.

Advantages of Polymorphism:

Helps the programmer to reuse the code.

Save time

Single variable can be used to store multiple data types.

Easy to debug the code

Reduces coupling between different functionalities

Example code for Polymorphism :

class Polygon {

// method to render a shape
public void render() {
System.out.println("Rendering Polygon");
}
}

class Square extends Polygon {

// renders Square
public void render() {
System.out.println("Rendering Square");
}
}

class Circle extends Polygon {

// renders circle
public void render() {
System.out.println("Rendering Circle");
}
}

class Main {
public static void main(String[] args) {

// create an object of Square
Square s1 = new Square();
s1.render();

// create an object of Circle
Circle c1 = new Circle();
c1.render();
}
}

Output

Rendering Square
Rendering Circle

--

--