Object Oriented Programming

What is Object Oriented Programming ?

Object Oriented Programming in Java is a back bone of any development. Understanding of OOP concepts will open a door for you to understand the code written by other developers and contribute.

OOP in Java has four key concepts.

Abstraction, EncapsulationInheritance, and Polymorphism.

 Abstraction

It means using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know how it works internally. So, we can say that all the complexities are abstracted out into a single remote-control button.

In Java, abstraction means classes. Inside class we have variables and methods. We create an instance of that class, often referred as an object and object behaves like a remote-control.

Example:

public class Employee {

      private String name;

       private int age;

       private double salary;

       private String nic;

       //Constructor with all fields

       public Employee(String name, int age, double salary, String nic) {

             this.name = name;

             this.age = age;

             this.salary = salary;

             this.nic = nic;

       }

    // Getters and setters

    public String getName() {

             return name;

       }

       public void setName(String name) {

             this.name = name;

       }

       public int getAge() {

             return age;

       }

       public void setAge(int age) {

             this.age = age;

       }

       public double getSalary() {

             return salary;

       }

       public void setSalary(double salary) {

             this.salary = salary;

       }

       public String getNic() {

             return nic;

       }

       public void setNic(String nic) {

             this.nic = nic;

       }

       // Method for calculating a bonous

       public double calculateBonous(int age, double salary){

             double bonous = (age*0.05) * (0.10 * salary);

             return bonous;

}

}


// Create a Test class

public class Test {

      public static void main(String[] args){

             //Create an instance of Employee

             Employee e1 = new Employee("John", 35, 10000.00, "ABC12345689");

             // Call a method (calculateBonous)

             e1.calculateBonous(e1.getAge(), e1.getSalary());

       }

}

Explanation:

We created a Class (blue print) of an Employee and gave a basic variables (attribute) to the employee, constructor method for creating an instance of Employee, getters and setters for all variables and a method (calculateBonous) which will be calculating bonus.

To test our abstraction concept, we created a Test class and inside a test class an Employee instance is created. Employee instance (e1) called a method calculateBonous directly. Now e1 will behave like a remote-control and all the complex operation are abstracted inside a method and method is abstracted inside the class.

Encapsulation

It is all about providing a private access to variables and make them accessible via getters and setters methods as we did in above example. It is a protective barrier that keeps the data and code safe within the class itself.

Now the question is, if variables are private and we are providing a public getters and setters methods to access them then how we are creating a protective barrier?

For example, if I am not allowed to do e1.name = “David” but I am allowed to do e1.setName(“David”) then HOW it is encapsulated and answer is very simple. Inside our setters or getters we do some checks and if those checks are passed then user will be able to set or get the variable.

public void setName(String name) {

       if(allowed){

             this.name = name;

       }

   }

Inheritance

This is a special feature of Object Oriented Programming in Java. It lets programmers create new classes that share some of the attributes of existing classes. This lets us build on previous work without reinventing the wheel.

It works by letting a new class adopt the properties of another. We call the inheriting class a subclass or a child class. The original class is often called the parent. We use the keyword extends to define a new class that inherits properties from an old class.

public class Animal {

      String name;

      String color;

      int age;

   public void makeSound(){

             System.out.println("My Sound is : ");

      }

}

public class Tiger extends Animal {

       String attack;

       public void makeSound(){

             super.makeSound();

              System.out.println("ROAR");

       }

}

public class Sparrow extends Animal {

       String feather ;

       public void makeSound(){

             super.makeSound();

              System.out.println("BEBE");

       }

}

Tigger and Sparrow are sharing name, color and age attributes and makeSound() method from the Animal class because they made themselves a child of Animal class by extending an Animal Class. However, they can also provide their attributes and methods.

public class Test {

       public static void main(String[] args){

             Tiger t1 = new Tiger();

             t1.makeSound();

       }

}

Output:

My Sound is :

ROAR

 

Polymorphism

Java OOPs concept lets programmers use the same word to mean different things in different contexts. Method overloading, method overriding and Interfaces are example of Polymorphism.

In method overloading, a single method may perform different functions depending on the context in which it’s called. That is, a single method name might work in different ways depending on what arguments are passed to it.

Example of method overloading:

public class Calculator {

             public int add (int num1, int num2){

             return num1 + num2;

       }

      public double add (double num1, double num2){

             return num1 + num2;

       }

}

In method overriding, the child class can use the OOP polymorphism concept to override a method of its parent class. That allows a programmer to use one method in different ways depending on whether it’s invoked by an object of the parent class or an object of the child class.

Example of method overriding:

public class ScentificCalculator extends Calculator {

       // Overriding add method

       public int add(int num1, int num2){

             System.out.println("Adding two number");

             return num1 + num2;

       }

}

Interfaces

Without going into details about Interfaces, lets discuss the how Interfaces support polymorphism?

Let’s take an example of Java Collection a List interface and ArrayList, Vector and LinkedList are implementing a List interface. If I want to print an instance of ArrayList or instance of Vector or instance of LinkedList then we need a separate print method. But thanks to polymorphism, we can use a same print method to print all the above Java collections.

Example

public class Test {

       public static void main(String[] args){

             List myArrayList = new ArrayList();

             List myVector = new Vector();

             List myLinkedList = new LinkedList();

             myArrayList.add(1);

             myArrayList.add(2);

             myArrayList.add(3);

             myVector.add(4);

             myVector.add(5);

             myVector.add(6);

             myLinkedList.add(7);

             myLinkedList.add(8);

             myLinkedList.add(9);

             System.out.println("Printing Array List");

             print(myArrayList);

             System.out.println("Printing Vector");

             print(myVector);

             System.out.println("Printing Linked List");

             print(myLinkedList);

       }

       public static void print(List myList){

             for (int i = 0; i < myList.size(); i++){

                    System.out.println(myList.get(i));

             }

       }

}