Wednesday 21 June 2017

Object Oriented Programming (OOPS) concepts

What is object oriented programming:

Object-oriented programming (OOP) refers to a type of computer programming (software design) in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

Mainly there are 4 different OOP concepts available in Java, they are,

  1. Inheritance
  2. Polymorphism
  3. Abstraction
  4. Encapsulation
Let's explore one  by one.

Inheritance:


Different kind of objects often have a certain amount in common with each other. Like Audi car, BMW car and etc for example, all share the characteristics of Car(current speed, current gear etc). Yet each also defines additional features that make them different: like brand, pricing, security etc.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In below example, Car now becomes the superclass of BmwCar, Hondacar and AudiCar. In the Java programming language, 


  • Each class is allowed to have only one direct superclass, and 
  • Each superclass has the potential for an unlimited number of subclasses.

extends is the keyword used to inherit the properties(states and behaviors) of a class. Syntax of extends keyword is shown in below example.

Let's see how above image is implemented in java. In below example, You can observe a super class called Car and 1 sub class(one sub class is enough to demonstrate Inheritance) BmwCar extending the Car class which is a super class.

Let's create super class named Car.java

Now let's create a new BmwCar.java class which will eventually extends Car class to become a child class.

Now let's create a main class where you start your Java program execution.

If you execute the MainClass.Java you will get below output,



The price of the car is:100000
Changing the gear to: 4
Increasing the speed to:60

In MainClass.java, we have created an object for the class BmwCar.java where it got only one method called getPrice(), but we are still able to access 2 other methods changeGear & sppedUp from Car.java. This is because BmwCar.java is inherited all the properties from it's extended super class which is Car.java.


Rules of Inheritance:

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
  • A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.


Polymorphism:


The dictionary definition of polymorphism refers to something which can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language.

Polymorphism in Java is same name but different forms. This can be achieved in 2 different ways,


Method Overloading:


It is a feature that allows a class to have more than one methods having same name but having different argument lists. It is also known as Static Polymorphism.

Method overloading can be done either with different number of parameters or with different type of parameters with same method name. Number of parameters can be same when you are overloading a method with different parameter types.

Like in below example we have 3 methods with same name "add" but they differ in either number of parameters or type of parameters.


public class MethodOverloading {

  int add(int a, int b) {
    return a + b;
  }
  //Overloading 1st method with different no. of params
  int add(int a, int b, int c) {
    return a + b + c;
  }
  //Overloading 1st method with different type of params
  float add(float a, float b) {
    return a + b;
  }
}

Method overloading can happen withing the same class like in above example or else it can also be achieved in case of Inheritance where child can have same method as in parent class but with the different parameter types or different number of parameters as said above. Lets see how this is achieved.


//Parent class
public class Calculator{

  int add(int a, int b) {
    return a + b;
  }
}

//Child class which extends super class Calculator
public class MyCalculator extends Calculator{

  //Overloading method of super class with different no. of params
  int add(int a, int b, int c) {
    return a + b + c;
  }
  //Overloading method of super class method with different type of params
  float add(float a, float b) {
    return a + b;
  }
}

At another side, method overloading cannot be achieved just changing parameter names,  Like,



  int add(int number1, int number2) {
    .....
  }

  int add(int num1, int num2) {
    .....
  }

or also overloading cannot be achieved just changing the return type,



  int add(int number1, int number2) {
    ....
  }

  float add(int number1, int number2) {
    ...
  }


Method Overriding:



Overriding means having two methods with the same method name and parameters type and number of parameters (i.e., method signature). This can only be achieved in case of Inheritance. i.e. One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a different implementation of a method that is already provided in it's parent class.



class Dog{
    public void bark(){
        System.out.println("woof woof");
    }
}

class MyDog extends Dog{
   
    @Override
    public void bark(){
        System.out.println("bow bow");
    }
}
 
public class MethodOverriding{
    public static void main(String [] args){
        Dog dog = new MyDog();
        dog.bark();
    }
}


Rules for method overriding:
  • In java, a method can only be written in Subclass, not in same class.
  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method’s access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

With Abstraction:

Abstraction is process of hiding the implementation details and showing only the functionality.

Abstraction in java is achieved by using interface or abstract class. Interface give 100% abstraction and abstract class give 0-100% abstraction.


What is Abstract class?

A class that is declared as abstract is known as abstract class.
An abstract class is something which is incomplete and you can not create an instance of the abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class.


What is Abstract method?


A method that is declared as abstract and does not have implementation is known as abstract method.
If you define abstract method than class must be declared a abstract. An Abstract class can have 0 - n number of abstract classes. An abstract class with an abstract method looks like below.



abstract class Dog{
    public abstract void bark();
}

class MyDog extends Dog{
   
    @Override
    public void bark(){
        System.out.println("bow bow");
    }
}
 
public class AbstractExample{
    public static void main(String [] args){
        Dog dog = new MyDog();
        dog.bark();
    }
}

In above example we made Dog class abstract and it has one abstract method without implementation. Then, who will provide the implementation? When a class is made abstract that class cannot be instantiated or an object cannot be created in other words. But any other class can only inherit means extend this abstracted class and provide the implementation to it's methods.
If the class which is extending the abstracted class does not provide implementation to the methods then it should also be declared itself as an abstract class.

When do you use abstraction?
  • If You want to share common code among several closely related classes.
  • If You want subclasses should provide the implementation of the abstract methods.

Interfaces:


Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules) which works as a common understanding document among various teams in software development.

In other words Interface is an agreement or bond which have to be obeyed by it's implemented classes. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

A normal class describes the attributes and behaviors of an object. But an interface contains behaviors that a class must implement.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

However, an interface is different from a class in several ways, including −

  • You cannot instantiate an interface. 
  • An interface does not contain any constructors. 
  • All of the methods in an interface are abstract. 
  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. 
  • An interface is not extended by a class; it is implemented by a class. 
  • An interface can extend multiple interfaces. 
  • An interface and it's methods are implicitly abstract. You do not need to use the abstract keyword while declaring an interface and it's methods. 
  • Methods in an interface are implicitly public.

The interface keyword is used to declare an interface. 

Implementing Interfaces:


When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
Lat's take an example of Central Bank where Account as an interface. It says every bank while opening an account for a customer must capture the details like name, date of birth and address. Now when bank BOI, AIB or etc must agree to the contract and implement this rules in their own bank. See below example.


interface Bank{
     void name();
     void dob();
     void address();
}

class Boi implements Bank{

    @Override
    public void name() {
      System.out.println("Account name is foo");
      
    }

    @Override
    public void dob() {
      System.out.println("DoB is bla bla");
      
    }

    @Override
    public void address() {
      System.out.println("Address is earth");
      
    }
}
 
public class Interfacing{
    public static void main(final String [] args){
      final Bank bank = new Boi();
      bank.name();
    }
}

A class can implement an Interface but an Interface can extend any number of interfaces. Interface is the only thing which allows multiple inheritance but not a class.



public interface Sports {
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

public interface BreakTimes {
   public void halfTime(int time);
   public void fullTime(int time);
}
//Extending single interface
public interface Hockey extends Sports {
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);
}
//Extending multiple inetrfaces public interface Football extends Sports, BreakTimes { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); }


Encapsulation:

Encapsulation in Java is a mechanism of binding the data (variables) and code acting on that data (methods) together as a single unit. 

This is achieved by making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. If you make your fields public, then that field will be exposed to other classes outside and those classes will have the capability of changing the value of that field variable. This is called tight coupling in coding terms. For this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. 


The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
See below example for better understanding.

public class Encapsulation{

   private String name;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

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

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

}

Advantages of encapsulation
  • It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code setName() and getName() can be changed at any point of time. Since the implementation is purely hidden for outside classes they would still be accessing the private field name using the same methods (setName() and getName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.
  • The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) which doesn’t need to change at any cost then we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
  • User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.


1 comment:


  1. This is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    iphone training institute in bangalore
    best iphone training institute bangalore
    ios app development in hyderabad

    ReplyDelete