Sunday, 16 November 2014

Polymorphism or simply In many forms

Polymorphism means many forms.
In computer terms we relate polymorphism as one of the founding stones of OOP and many Programming Languages.

When an Object has the ability to take more than one form it is referred to as Polymorphic. When a parent class reference is used to point to an object of it's child it is termed as a polymorphic reference.

When we talk about method polymorphism in Java, Compile Time and Run Time are two of its types.

Compile Time Polymorphism or Method Overloading is achieved when the methods have the same name and quite possibly process the input in a similar manner but take different inputs; either the number or the types of input are different. Method Overloading works when all the methods that you wish to overload are in the exact same class.
Let's take an example ...
public class JavaBlink {
    // This method takes two arguments and return there sum
    public int sum(int o1, int o2) {
        return o1 + o2;
    }
   
    // This method takes three arguments and return there sum
    public int sum(int o1, int o2, int o3) {
        return o1 + o2 + o3;
    }
In the example above you could see that I have used different number of arguments and overloaded the method sum. This is one of the simplest forms of method overloading.

Run Time Polymorphism on the other hand, as the name suggests, happens when the program is actually executed after compilation. This requires at least two classes or one class and one interface, both of which should be in a hierarchy.
Let's take an example ...
public class Earth {
    public float checkGravity() {
        return 9.78f;
    }
}

public class Moon extends Earth {
    public float checkGravity() {
        return 1.622f;
    }
}

public class Tester {
    public static void main(String[] a) {
    // creates an object of type Earth with reference type Earth
        Earth earth = new Earth();      
  
    // creates an object of type Moon with reference type Moon
        Moon moon = new Moon();      
       
    // creates an object of type Moon with reference type Earth
    // This is where the polymorphism kicks in; At runtime the call
    //    is sent to Moon's checkGravity()
        Earth polyMoon = new Moon();  
       
        System.out.println(earth.checkGravity());
        System.out.println(moon.checkGravity());
        System.out.println(polyMoon.checkGravity());
    }
}

In Java, specifically, we can use polymorphism in a variety of ways ...

1. Methods can be made polymorphic to cater to a wide variety of inputs
2. Polymorphic references as method arguments can be used where a variety of SubTypes could be passed; though care should be taken when calling methods on received objects
3. Polymorphism is the driving force behind Strategy Design Pattern

Sunday, 7 July 2013

Encapsulation - Let's Hide

Encapsulation ...

In Simple words it means "the process of enclosing" which further means "surround completely".

Encapsulation hides the implementation details from the outside code which in turn provides high flexibility and maintainability. The classes thus written are loosely coupled and change in one class doesn't accounts for a change in some other class that access it. Due to this we can rewrite our class to append any new change without affecting any other code.

Now. How can we do that ?
  1. By keeping Instance variables protected from outside code (usually making it private)
  2. By creating accessor methods and restrict outside code from directly accessing the instance variables (use JavaBeans naming convention to create accessors).
 

Wednesday, 8 May 2013

Difference between an Interface and an Abstract Class ???

Let's first summarize the two of them ...

An Interface - is much like an agreement that declares the characteristics and capabilities of a Class that implements it.

An Abstract Class - is more like a conceptual subset of a class that extends it.

Now, Lets talk about them in depth ...

Abstract Classes ...
  • cannot be instantiated
  • have abstract methods i.e only declaration part of a method
  • can also have non-abstract methods
  • can have data members as well
  • must be subclassed to be used
  • must be declared as abstract
  • can extend other classes
  • can implement interfaces
public abstract Class Automobile {
   private int wheels;
   public abstract travel();
}    

Interface ...
  • is much like 100% abstract classes
  • cannot be instantiated
  • data members are implicitly public static final
  • methods are implicitly public abstract
  • can only extend other interfaces, it cannot extend a class or implement an interface
  • can be used polymorphically
  • can be implemented by any class within any hierarchy

    public interface moveable {
       int wheels;
       travel();
    }    

Sunday, 5 May 2013

What is Casting ???

Casting lets you convert one type of value into another.
In general terms casts can be implicit as well as explicit.
Let's dig some more into it ...

Implicit casts are those for which you do not have to write the code yourself i.e. it happens automatically. for Explicit casts code is required to be written by the developer.

Implicit casts are the often termed as widening conversions, for a smaller value can always be put into a larger container if the semantics of the data types involved are appropriate.

Explicit casts are used for narrowing conversions where a larger value is to be fit into a smaller container. Again the semantics of the involved data types must be appropriate.

Casting can be described in terms of
1. Primitive Data Types
2. Reference  Variables

Let's talk about Primitive Data Type Casting first...

int a = 100;
long aa = a; // Implicit cast, an int can always fit in a long

float f = 100.234;
int i = (float)f; // Explicit cast, float will loose it's decimal notation

In the above two examples Implicit and Explicit casts are shown in their simplest forms... let's see a few more examples to understand.

int i = 100.234; // error; a cast is very much required.
int i = (int) 100.234; // works

Let's take a look at casting involving Reference Variables

Suppose, we have this hierarchy ... 
Animal >>> Mammal >>> Dolphin

Dolphin dolphin = new Dolphin();
Mammal mammal = dolphin;
Animal animal = mammal;

Above written code is a classic example of an Implicit casting or sometimes also referred to as Upcasting.



if(animal instanceof Mammal) {
    mammal = (Mammal) animal;
}

Above code is an example of an Explicit cast or a Downcast.

In case of an Upcast, an error can only arise if the two reference variables do not fall in the same hierarchy or if the container reference falls below in the same hierarchy.

Implicit cast also comes with a small cost. When you upcast a reference variable, it can then only call those methods and only access those data members which are a part of the new Reference type.

Class Animal { // Animal Class
 public int getLegs() {
   return 4;
 }
}

Class Mammal extends Animal { // Mammal Class
 public int getEyes() {
   return 2;
 }
}

Class Test {
   public static void main(String... s) {
     Mammal mammal = new Mammal();
     Animal animal = mammal; // correct, legal
     
     mammal.getLegs(); // correct 
     mammal.getEyes(); // incorrect, Eyes() is a part of the mammal class
   }

In the above example mammal.getEyes() will throw an Exception at runtime because Animal class has no knowledge of the getEyes() present in the Mammal class. Reference variable "animal" can only be used to call those methods which are present in the Animal Class only.



Tuesday, 30 April 2013

Access Specifiers and Visibility of data member

VisibilityPublicProtectedDefaultPrivate
Within the Same ClassYesYesYesYes
From a class within the same packageYesYesYesNo
From a subclass within the same packageYesYesYesNo
From a subclass outside the packageYesYes, through InheritanceNoNo
From a non-subclass outside the packageYesNoNoNo

Sunday, 28 April 2013

Difference between equals() and ==

"equals()" and "==" are both used for checking the equality of two variables. 
A small difference is there though. 

  1. equals() checks for "value based equality" while "==" checks for reference equality.
  2. equals() is a method and can only be used in conjunction with an object while "==" is an operator and can be used for primitives and objects both
  3. equals() is a part of the Object class
  4. equals() can be overloaded and you can give your own meaning to it which is not possible with the "==" operator
  5. "==" when used with a primitive checks for the value help by the variables. On the other side when "==" is used with a reference variable it checks if the two reference variables point to the same object.

Saturday, 27 April 2013

How Pass by Value works in Java ???

In Java Pass by Value is everywhere ... whenever you pass an argument to a method in Java it is passed as a value. 

In Java, the primitives datatypes as well as the Class objects are passed by value only. 
By value i mean a copy of the original.
Let's take up a small example ...

public int doSomething(int val1, int val2) {
      val1 += 5;
      val2 += 10;
      return val1 + val2;
}

public static void main(String... args) {
     int val1 = 5;
     int val2 = 10;
     System.out.println("val1 = " + val1 + " , val2 = " + val2);
     int val3 = doSomething(val1,val2);

    
System.out.println("val1 = " + val1 + " , val2 = " + val2 + " , val3 = " + val3);
}

 As you can see in this example the two syso's print the same value of val1 and val2 before and after they are passed to the doSomething()

Now, if we talk about Class Objects, a copy of the object is passed as an argument to the method and the original object remains unchanged.