Sunday, February 23, 2014

Method Overriding in Java

Advantage of Java Method Overriding:

    1) Method Overriding is used to provide specific implementation of a method that is         already provided by its super class.
    2) Method Overriding is used for Runtime Polymorphism

Code Example:

    In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. 

    class Engine{ 
    void run(){System.out.println("Engine is running");} 
    } 
    class Car extends Engine{ 
    void run(){System.out.println("Car is running Successfully ");} 
     
    public static void main(String args[]){ 
    Car obj = new Car(); 
    obj.run(); 
    } 

Output:
 
   Car is running Successfully

Wednesday, February 19, 2014

Synchronized block


Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then Java synchronized block will throw a NullPointerException.

public class Singleton {
   private static Singleton instance;
   public static Singleton getInstance()
   {
            if(instance == null) {
                  synchronized(Singleton.class){
                           if(instance == null) {
                                 instance = new Singleton();
                         }
                   }
            }
          return instance;
       }
   }

Java Collections - hashCode() and equals()

The methods hashCode() and equals() play a distinct role in the objects you insert into Java collections. The specific contract rules of these two methods are best described in the JavaDoc. Here I will just tell you what role they play. What they are used for, so you know why their implementations are important.

equals():

equals() is used in most collections to determine if a collection contains a given element. For instance:

List list = new ArrayList();
list.add("123");
boolean contains123 = list.contains("123");

The ArrayList iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". It is the String.equals() implementation that determines if two strings are equal.
The equals() method is also used when removing elements. For instance:

List list = new ArrayList();
list.add("123");
boolean removed = list.remove("123");

The ArrayList again iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.

As you can see, a proper implementation of .equals() is essential for your own classes to work well with the Java Collection classes. So how do you implement equals() "properly"?

Code:

public class Employee
{
    private Integer id;
    private String firstname;
    private String lastName;
  
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 

  
   @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
        Person guest = (Person) obj;
        return id == guest.id
                && (firstName == guest.firstName
                     || (firstName != null && firstName.equals(guest.getFirstName())))
                && (lastName == guest.lastName
                     || (lastName != null && lastName .equals(guest.getLastName())));
    }
   
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + id;
        result = prime * result
                + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }
}

import java.util.HashSet;
import java.util.Set;
public class EqualsTest
{
    public static void main(String[] args)
    {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        e1.setId(100);
        e2.setId(100);
        //Prints 'true'
        System.out.println(e1.equals(e2));
        Set employees = new HashSet();
        employees.add(e1);
        employees.add(e2);
        //Prints two objects
        System.out.println(employees);
    }
}