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.

Wednesday 24 April 2013

Difference between 'pass by value' and 'pass by reference'

Pass by Value - This means passing the actual value of the variable as an argument to some method.

Pass by Reference - This means passing the reference to the variable as an argument to some method.

Now the question ??? What does Java Use from among the two ??? 

Java is actually pass by value for all the variables within a single VM.

Tuesday 23 April 2013

How JavaBeans differ from POJO's ???

JavaBeans are governed by certain Java Specifications which a POJO is free from.

The JavaBean specification requires a java class to ...
  1. be Serializable
  2. have getters and setters
  3. have a no argument
JavaBean Property Naming Rules ...
  1. If the property is not a boolean, the getter method's prefix must be get e.g. getSize()
  2. If the property is a boolean, the getter method's prefix should be either get or is e.g. getEmpty(), isEmpty()
  3. The setter method's prefix must be set e.g. setSize()
  4. Name of the getter or setter method is completed by changing the case of the first letter of the property name to UPPERCASE e.g. if property is size then methods are getSize() and getSize()
  5. setter methods should be marked public with void return type with an argument that represents the property type
  6. getter methods should be marked public, take no arguments, and have a return type that matches the argument type of the setter method

Sunday 21 April 2013

What is a Plain Old Java Object or POJO ???

A "POJO" is an ordinary Java Object which does not follow any of the major Java object models, conventions, or frameworks.  

A "POJO" however is bound by the restrictions forced by the Java Language Specification.

Some of these restrictions are ... 

  1. A POJO cannot extend any Class
  2. A POJO cannot implement any Interface
  3. A POJO cannot contain any prespecified annotation 
An example of a simple POJO may be ...

public class POJO {
 
    private String someProperty;
 
    public String getSomeProperty() {
         return someProperty;
    }
 
    public void setSomeProperty(String someProperty) {
        this.someProperty = someProperty;
    }
}