Friday, August 23, 2013

Eclipse IDE: Snippet/Template



1) Window → Preferences → Java → Code Style→ Code Templates→ Comments -> Files
Click Edit
and Copy and paste:

/****************************************************************************
*
*                    Copyright (c), ${date}
*                    All rights reserved
*
*                   COMPANY_NAME, INC
*                    CITY, STATE
*                    COUNTRY
*
****************************************************************************
* File Name: ${file_name}
*
* $$Log $$
*
* @Autor: ${user} : ${date}
*
*/

2) In Window → Preferences → Java → Code Style→ Code Templates→ Code-> New java File
Click Edit
and Copy and paste:
${filecomment}
${package_declaration}

${typecomment}
${type_declaration}

3) Select: "Automatically add comments for new methods and types"

So every time you create a new class this header is added

Thursday, April 18, 2013

Polymorphism, Inheritance, Encapsulation

Polymorphism


Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

In Java programming whole concept of interface is based on Polymorphism and its a famous design principle that to code for interface than implementation to take advantage of Polymorphism and introducing new implementation in future.



Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

An important example of polymorphism is how a parent class refers to a child class object.  In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature.

For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super class Animal.
Note: It’s also legal to say every object in Java is polymorphic in nature, as each one passes an IS-A test for itself and also for Object class.

Static Polymorphism:
In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method signatures.  So, this is called compile time polymorphism or static binding. The concept will be clear from the following example:

class DemoOverload{
    public int add(int x, int y){  //method 1
    return x+y;
    }
    public int add(int x, int y, int z){ //method 2
    return x+y+z;
    }
    public int add(double x, int y){ //method 3
    return (int)x+y;
    }
    public int add(int x, double y){ //method 4
    return x+(int)y;
    }
}
class Test{
    public static void main(String[] args){
    DemoOverload demo=new DemoOverload();
    System.out.println(demo.add(2,3));      //method 1 called
    System.out.println(demo.add(2,3,4));    //method 2 called
    System.out.println(demo.add(2,3.4));    //method 4 called
    System.out.println(demo.add(2.5,3));    //method 3 called
    }
}


In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters.  The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time.

Dynamic Polymorphism:

Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.
Have a look at the following example.
class Vehicle{
    public void move(){
    System.out.println(“Vehicles can move!!”);
    }
}
class MotorBike extends Vehicle{
    public void move(){
    System.out.println(“MotorBike can move and accelerate too!!”);
    }
}
class Test{
    public static void main(String[] args){
    Vehicle vh=new MotorBike();
    vh.move();    // prints MotorBike can move and accelerate too!!
    vh=new Vehicle();
    vh.move();    // prints Vehicles can move!!
    }
}
It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.
As the method to call is determined at runtime, this is called dynamic binding or late binding.

Summary:

An object in Java that passes more than one IS-A tests is polymorphic in nature
Every object in Java passes a minimum of two IS-A tests: one for itself and one for Object class
Static polymorphism in Java is achieved by method overloading
Dynamic polymorphism in Java is achieved by method overriding
 

Friday, April 12, 2013

Java Collections



Java.util

Collections can store only objects in Java. Primitive types can not be added to a collection, so it is necessary to use the wrapper classes such as Integer and Double instead of primitives.

There are three elements that make up collections.
·        Interfaces  define the methods that each type of collection must implement
·        Implementations  actual classes such as Hashtable and Vector
·        Algorithms  methods that store, retrieve, and manipulate elements in a collection

There are four properties that collections may or may not possess, as shown in Table. These are the properties you must know to differentiate collection types.

Property

Description

Sorted
Ascending order, sorted naturally using the equals() object method. An example is a Membership list.
Ordered/Unordered
Collection keeps an order determined by where the object is placed in the collection. For example, a deck of cards is ordered.
Allows duplicates
Duplicate objects can be added to the collection. An example is a collection of hockey cards.
Uses keys
A key object is used to reference the stored object. For example, names of people are stored by social insurance number.


Collection Interfaces and Classes
The interfaces in the collections framework are the foundation of collections. By using these interfaces, collections can be passed into other methods regardless of the details of a particular collection.
There are six interfaces that make up the core collections framework. Some of these interfaces extend other interfaces to form a hierarchy
                             

Notice Map and SortedMap do not extend the Collection interface. Map and SortedMap are still known as collections, even though in strict Java terms they are not Collection types.








Each of the interfaces also has an abstract class that has some of the methods already programmed. For example, the Collection interface has a class called AbstractCollection, and the Set interface has a class called AbstractSet.







We will now examine the interfaces individually.

Iterator methods

A simple explanation of an iterator is an object that contains methods that allow a programmer to iterate through the data one element at a time.Iterator enables you to cycle through a collection, obtaining or removing elements.

List al = new ArrayList();
      // add elements to the array list
      al.add("A");
      al.add("B");
      al.add("C");

// Use iterator to display contents of al
Iterator itr = al.iterator();
while(itr.hasNext()) {
         Object element = itr.next();
}
Iterator iterator()
The iterator() method returns an Iterator object from the collection. The methods in the Iterator interface are as follows:
boolean hasNext()
This returns true if the iteration has more elements.
Object next()
The preceding returns the next element in the iteration.
void remove()
This removes from the underlying collection the last element returned by the iterator.

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

ListIterator litr = al.listIterator();
while(litr.hasNext()) {
   Object element = litr.next();
   litr.set(element + "+");
}
while(litr.hasPrevious()) {
   Object element = litr.previous();
}  

Set

A Set is unique because it does not allow duplicate objects to enter the collection of elements. The Set interface contains all of the methods of the Collection interface  and does not add any new methods. The difference is the add() and addAll() methods check for duplication of objects using the equals() method on each object.
The only functional class in the Java API that directly implements the Set interface is HashSet, as you can see in the Figure. Let’s look at the HashSet class in use.
import java.util.*;
class SetTest {
     public static void main (String [] args) {
            Set<String> hs = new HashSet<String>();
          hs.add("Hockey Game");
          hs.add("Poker");
          hs.add("Solitaire");
          hs.add("Hockey Game");
          System.out.println(hs);
     }
}

Sorted Set

The SortedSet interface is similar to the Set interface, except that the elements in the set are stored in ascending order. Once again, the elements are nonduplicating. The SortedSet interface includes all of the methods of Set because it extends Set, but also adds a few more to take advantage of the fact that it is sorted.
The TreeSet class is the only class to implement this interface directly. Let’s examine the TreeSet class in some code.
import java.util.*;
class SortedSetTest {
     public static void main (String [] args) {
          SortedSet set = new TreeSet();
          set.add("Hockey Game");
          set.add("Chess");
          set.add("Checkers");
          set.add("Blackjack");
          System.out.println(set);
          SortedSet end = set.tailSet("Checkers");
          System.out.println(end);
     }
}

List

A List is ordered. This allows a List to maintain an order as objects are added and removed from the collection. This is not the same as sorted! Sorted objects form a hierarchy based on how the objects compare to each other, such as alphabetical sorting.



Note: An ordered collection maintains the order of the elements based on the sequence you put stuff into/remove them from the collection. A sorted collection keeps the elements sorted based on a sort criteria.
 
A List can also contain duplicate entries of objects. The List interface adds several methods, all of which deal with the List collection being ordered. The added methods contain an index or index numbers that are used to specify a certain ordered object in the List.
There are three functional classes that implement the List interface.
·        LinkedListobjects are queued at the beginning of the list and removed from the end. Often used when buffering operations.
·        Vectora growable array of objects.
·        ArrayListThis class is roughly equivalent to Vector, except that it is unsynchronized.

  LinkedList ArrayList
get(int index)  O(n) (with n/4 steps on average) O(1) <--- main benefit of ArrayL
add(E element)  O(1) O(1) amortized, but O(n) worst-case
add(int index, E element)  O(n) (with n/4 steps on average), but O(1) when index = 0 O(n) (with n/2 steps on average)
remove(int index)  O(n) (with n/4 steps on average) O(n) (with n/2 steps on average)
Iterator.remove()  O(1). <--- main benefit of LinkedList<E> O(n) (with n/2 steps on average)
ListIterator.add(E element) O(1) This is one of the main benefits of LinkedList<E> O(n) (with n/2 steps on average)

 

 

Map

The Map interface does not extend the Collection interface (see figure), so in strict terms it is not a Collection type. In general terms, however, it is part of the collections architecture.
A Map stores objects that are identified by unique keys. A map may not store duplicate keys. It can, however, store duplicate objects. Objects are stored in Map collections in no particular order.
There are two common collections that directly implement the Map interface, as we saw in Figure:
·        Hashtable
·        HashMap
The HashMap class is roughly equivalent to Hashtable, except that it is not synchronized for threads and it permits null values to be stored.
import java.util.*;
class HashMapTest {
     public static void main (String [] args) {
          Map hm = new HashMap();
          hm.put("Game1","Tic Tac Toe");
          hm.put(null, "Chess");
          hm.put("Game3", "Checkers");
          hm.put("Game3", "Hockey Game");
          hm.put("Game4", "Chess");
          System.out.println(hm);
          String title = (String)hm.get("Game3");
          System.out.println(title);
     }
}

Sorted map

SortedMap is similar to Map, except the objects are stored in ascending order according to their keys. Like Map, there can be no duplicate keys and the objects themselves may be duplicated. One very important difference with SortedMap objects is that the key may not be a null value. SortedMap objects are, of course, sorted and it would be impossible to try to sort with a null value as a comparator.
TreeMap is the only core API class to implement this interface directly, so let’s examine this in some code.
import java.util.*;
class TreeMapTest {
     public static void main (String [] args) {
          Map titles = new TreeMap();
          titles.put(new Integer(2),"Tic Tac Toe");
          titles.put(new Integer(3), "Checkers");
          titles.put(new Integer(1), "Hockey Game");
          titles.put(new Integer(4), "Chess");
          System.out.println(titles);
     }
}


 
Sorted
Ordered
Uses Keys
No Duplicates
Set
 
 
 
X
SortedSet
X
 
 
X
List
 
X
 
 
Map
 
 
X
 
SortedMap
X
 
X


Now that you have a better idea of collections, here are some possible attributes for a collection, followed by the correct collection interface.

Non-duplicating, unordered collection
Set
Duplicating, ordered collection
List
Duplicating, ordered collection with keys
Map
Non-duplicating, sorted collection
SortedSet
Duplicating collection sorted by keys
SortedMap

·         Set can store only unique objects, not duplicates.
·         A List keeps the objects indexed in a definite order.
·        A Map stores objects according to keys.
·        SortedSet stores objects in ascending order without duplicates.
·        SortedMap stores objects in ascending order using keys.
·        SortedSet can’t contain objects that are null.
·        SortedMap can’t contain keys that are null.
·        HashSet implements the Set interface.
·        TreeSet implements the SortedSet interface.
·        LinkedList, Vector, and ArrayList implement List.
·        HashMap and Hashtable implement the Map interface.
·        TreeMap implements the SortedMap interface.