Friday, 23 August 2013

Polymorphism - Method Overloading and Method Overriding

Polymorphism


Polymorphism, in Greek means “many forms”. It simply refers to the different behavior of same thing in different ways according to the situations based on type of inputs. It simply works on the fundamental of message passing.

Consider the real time example of a Fund transfer:
Consider fund transfer as the common functionality used. Now based on the option selected for payment type the payment will be done i.e. the type of transaction as RTGS or NEFT can be selected by us and the transfer will take place based on that input. Thus you can see how same functionality behaved differently based on the types of mode.

Secondly, consider our sight as one function. If we see a lion coming towards us, we will run while if it’s a rabbit, we will go towards it. Here seeing is a function which is behaving in different manner based on the type of animal we are seeing.

Polymorphism in JAVA is one of the OOP concepts along with inheritance, encapsulation and abstraction. It helps in making the code more flexible and reusable for future enhancements.
It is achieved in two ways:
Static Polymorphism (method overloading)
      Dynamic Polymorphism (method overriding)

1.      Static Polymorphism :
This is termed as overloading /compile time binding. Here the compiler decides which method would be called based on the type/number of parameters getting passed while calling the method. The binding happens at compile time.
Overloaded methods are methods which have different signature. Method signature includes name, number of arguments, and type of arguments and order of arguments to that method.
So the overloaded methods

a.       Have the same name.
b.      Have different parameter list.(number of parameters/type of parameters/order of parameters)
c.       May appear in same class or subclass.

For example: see the below code snippets to understand different ways for overloading a method.

types of overloading methods
  
Constructor overloading is one of the application of static polymorphism in which a class can have multiple constructor with same name varying in list of arguments getting passed to it. It is as shown in below code.

Constructor Overriding



2.      Dynamic Polymorphism:
This is termed as overriding or run-time binding. In this type of polymorphism, the calling method is decided at run time based on the type of object calling the method. The overridden methods have the same name and same signature.  Overriding helps in achieving flexibility and extensibility as the new functionality can be introduced with minimal changes in the code.

Overriding methods:

a.      Can not appear in same class. They need to be defined in sub class.
b.     The accessibility of the overridden method cannot be reduced i.e. for example public method cannot be made private/default/protected in sub class.
c.      The private or static or final methods cannot be overridden.
d.      Signature and name must be exactly same.
e.      Overriding method cannot throw a checked exception which is higher in hierarchy than what is thrown by the overridden method. For example: If overridden method has thrown an IOException then the overriding method cannot throw java.lang.Exception.
         
       This will be clear with the below code:
       The base class is Shape which has one method defined as Area() which will be overridden in the sub            classes Circle and Rectangle. 

Base Class


Circle sub class extending Shape class. Area() method is oerridden



Rectangle sub class extending Shape class and overriding Area() method.

Main class calling different methods with different objects

     The result for above class execution is as below. It is clear that the methods are getting called based on the type of object which is getting created.


Sunday, 18 August 2013

Simplifying Encapsulation

Encapsulation

                Encapsulation in very simple terms means data/information hiding. Encapsulation is a process or mechanism which binds the data and methods together and keeps them safe from outside interference, misuse and access. It is about not allowing arbitrary access to the code written in one module from other modules. The access to these codes is provided through a well defined interface.

Let’s take a real world example to understand the concept.

In a vehicle, there are several parts being used in the engine like shaft, valves, piston, heater etc. But if we see, we are not affecting any of these components and their functionality.We are given just one interface to use them is to start the engine. In this way the internal details are kept unaffected from external impact and similarly the engine parts are not affecting anything outside.

                Coming to Java, the encapsulation is achieved by a class. A class is a blue print for a real time entity defining its structure and behavior. The data defined in a class are known as member variables/instance variables and the code which operates/manipulates the data are known as member methods.

Below image explains the use of encapsulation:

Encapsulation explained in pictorial view 



                   Private methods/private variables are accessed only by the same class. Public variables/methods are exposed to outside world to access the private data.

                  To hide the complexity, methods and variables are declared with the access specifiers. Typically variable are declared as private and the methods as public.

Private: accessible within the class.

Public: accessible from anywhere.

Default: accessible within the package.

Protected: accessible from all the sub classes within same/different packages.


A sample class code would look like as below:

A sample class code


Here the private member variable cannot be accessed from outside this class, so public getter and setter methods are declared to access from outside only through these methods.

Saturday, 17 August 2013

Abstraction simplified

Abstraction


Abstraction is an essential element of object oriented programming. Abstraction is used to manage the complexity of an implementation. Through Abstraction, relevant details are shown and irrelevant details are hidden.
For example, A car is driven by a person without knowing its internal architecture and construction. Here the relevant work for a person is to drive so other details like that of engine is not needed to be provided to him and thus abstraction comes into the picture.
The abstraction can be achieved by hierarchical classification of a complex system.
For example, If we take the example of a Car as a single object. It consists of several sub systems such as Seat, Brakes, Steering, Engine etc. and similarly these subsystems are again made up of more specialized parts.

Abstraction implementation in Java

In Java, Abstraction is achieved by declaring the methods without any implementation in interface or class and then defining these methods in the derived classes. This simply means that the actual definition of what a method will do is left for implementation on the class which can define the method according to the need. Abstraction is used when we know that something has to be there but not sure how exactly it should look like.
there are two ways to implement and attain the abstraction.
1. Abstract Class
2. Interface

1. Abstract Class : 

                             An Abstract class is a class of which no instance is created. To use an abstract class, it needs to be extended and the derived class must not have any abstract method. Abstract methods are declared in the abstract class which does not contain any method body. To use this method, it needs to be overridden in the sub class extending this abstract class.

For example :
When we have to create a class Shape, we know that each shape must have the method called area() but it may have different implementation for different types of shapes
skeleton for Abstract class is as explained below :
one abstract class Shape is created with two abstract methods area() and perimeter().

Abstract class Shape 








The Circle and Rectangle class extends this abstract class and they need to implement the abstract methods of Shape class. A shown below, both methods are implemented as per the type of shape. Her we can see that every shape needs to have its area and perimeter, thus these are defined in the abstract class and then implemented in the derived class and every subclass of this base class will have to implement these methods.

Derived class Circle

Derived class Rectangle

2. Interface: 

                   It is another way to implement Abstraction in java. Interfaces are just like classes with its all member variables defined as public, final and static i.e. no instance variables and all methods as abstract and public. It is denoted with keyword interface. The classes can implement any number of interfaces and any number of classes can implement same interface. the implementing class must define all the methods declared in the interface. Interfaces are created when we know that what a class must do but not how to do.
Like Abstract class, interface van not have any concrete method in it.
An interface abstraction is implemented like as below:
Shape is one interface and Circle and Rectangle are two classes which implement this interface.

Interface definition

Circle class implements Shape interface


Rectangle class implements Shape



.






















































When to Use Interface and When to use Abstract Class

  1. When we know that one functionality should be same across all the sub classes, Abstract class is to be used. For example : Every vehicle must have a method called start() which should be their in every vehicle derived     and its implementation must be same.
  2. When we use Interface, there is always a possibility that we can implement more than 1 interfaces thus multiple inheritance can be used.

Thursday, 15 August 2013

Features of JAVA - Reasons to use java over other languages

Java - Features

Java was developed by James Gosling, Chris Warth, Patrick Naughton, Ed Frank and Mike Sheridan at Sun Microsystems Inc. in 1991 which was initially termed as 'Oak' and later renamed to 'Java' in 1995. The fundamental necessities which led to evolution of java were portability and security.
There are several reasons on why to use java as the programming language over other languages. Few of them are as listed below:

Salient features of JAVA: 

Platform Independent
It is also termed as Write Once, Run Anywhere, any time, forever . A Java program that is written and compiled in one platform can run on any other platform without any recompilation or modification. This was achieved with the creation of Java Virtual Machine(JVM). The JVM is an interpreter which is platform dependent. All the JVMs accept the same input i.e. byte code and interpret it into machine language format of the corresponding platform. the basic flow is as given in below diagram.

basic flow in java programming

Simple
Java is designed in such a way that a professional programmer can learn it very easily and effectively.It is even better for a person to learn it if he understands the basic concepts of object oriented programming or has experience in C/C++.

Secured
It is one of the most innovative aspect of Java. It is achieved by confining an applet to the Java execution environment and not allowing access to other parts of the computer where the applet is downloaded. This is ensured by the use of JVM which is in control, can contain program  and prevent it from generating the side effects.

Potability
Portability becomes very important feature when we move to internet as many different types of computers and operating systems are connected to it. One single java program must be running on different kinds of CPU's, operating systems or browsers. this is achieved when we have the byte code of the java program which can be run on variety of environments as only JVM needs to be implemented there on platform.

Object Oriented
Java is one of the most powerful OOP languages.The Object model in java is simple and very easy extend. Java provides ways to implement all OOP concepts like Inheritance, Polymorphysm, Abstraction, Encapsulation and many more.

Robust
When it comes to a multi-platformed environment, reliability becomes the most demanding aspect of a program. Java forces you to find your mistakes early in the programming. Compile time and run time checks implemented in java helps to be free of worries about very common causes of errors. two very important feature to be considered for robustness in java are Memory management and Exception handling.

Multithreaded
java supports multithreaded programming which allows a programmer to write programs that can perform different actions simultaneously. In this feature, multiple light weighed process can run concurrently to use resources more effectively.

Distributed
Java handles TCP/IP protocols thus can be used for programs in distributed environment. Java also supports Remote Method Invocation (RMI) which makes it possible to call method from one program across the network.

High Performance
Just-in-time compiler plays the big role in making java with high performance. this converts the byte code in the native machine code for efficient outputs.