There may be times where one may think that I can extend parent class instead of implementing interface. Lets see whats When to choose inheritance over an interface and interface over inheritance.

inheritance over an interface
The main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for the evolution of APIs. Once you ship an interface, the set of its members is fixed forever. Any additions to the interface would break existing types implementing the interface.

A class offers much more flexibility. You can add members to classes that you have already shipped. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function unchanged.

interface over inheritance
Lets take the following code

Mammal.java

public abstract class Animal
{
 public void abstract mate();
 public void abstract feed();
}

Now the above abstract class has two methods mate() and feed().

public class Dog extends Animal
{
}

public class Cat extends Animal
{
}

Now we have Dog and Cat concrete classes extending Animal.

we have few more classes extending Animal

public class Giraffe extends  Animal{}
public class Rhinoceros extends  Animal{}
public class Hippopotamus extends  Animal{}

Now the classes Dog and Cat are pet animals. So it should implement pet behavior. This can be done in two ways.

  1. By defining isPet() method in base class and overriding in child class
  2. By implementing pettable interface.

Now implementing interface is easy compared to overriding method defined in base class because

  1. Interface favours clean code. Defining and Overriding the class may increase code redundancy
  2. Now you get a parakeets which is again a pet and could also fly.If you are inheriting the base class then you need to add canFly() method in base class and set it to return false and override in the parakeets class to return true.

    public class  parakeets extends Animal
    {
      .
      .
        public boolean canFly()
        {
            return true;
        }
    }
    

    Instead you can declare a interface flyable and implement the interface method without making changes to base class

    public class  parakeets extends Animal implements flyable 
    {
      .
      .
        public boolean canFly()
        {
            return true;
        }
    }
    
  3. Interface may be completely not related to class in which it is implemented. Say lets define a carpenter ants class which always moves one after another.Now this can be represented to implement queuing interface which has nothing to do with other animals other then carpenter ants since only ants of this type follows a queue system when they migrate from one place to another

Scenario 1:
If you have a clear analysis and Design in UML then you can start with the interface.

Scenario 2:
The interface shows up when you need to refactor common features out of several classes.Until you have multiple classes with common features, it’s hard to foresee what the interface should be.

Write a class and extract interface later. Usually the reason for extracting an interface is the need for a second implementation of that interface (often as a mock for unit testing)

  1. equals will only compare what it is written to compare, no more, no less.
  2. if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
  3. If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
  4. Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.

With respect to the String class:

The equals() method compares the “value” inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn’t make a difference. Its the “value” (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”..duh. If, on the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.

You will have to override the equals function (along with others) to use this with custom classes.

The equals method compares the objects.

“==” is an operator and “equals” is a method. operators are used for primitive type comparisons and so “==” is used for memory address comparison.”equals” method is used for comparing objects.

The Behavior of equals on class which is final is different.So it is on ENUM.

final class A
{
    // static
    public static String s;
    A()
    {
        this.s = new String( "aTest" );
    }
}

final class B
{
    private String s;
    B()
    {
        this.s = new String( "aTest" );
    }

    public String getS()
    {
        return s;
    }
}

First is the Normal working of equals over a String

public final class MyEqualityTest
{
    public static void main( String args[] )
    {
        String s1 = new String( "Test" );
        String s2 = new String( "Test" );

        System.out.println( "\n1 - PRIMITIVES ");
        System.out.println( s1 == s2 ); // false
        System.out.println( s1.equals( s2 )); // true
    }
}

Now lets see how equals work in final class

 A a1 = new A();
 A a2 = new A();

System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true

In the above you can see that a1.s == a2.s is true.This is because s is static variable and its is possible to have only one instance.(Investigate Further)

Third case is which is well know.

  B b1 = new B();
  B b2 = new B();

  System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
  System.out.println( b1 == b2 ); // false
  System.out.println( b1.getS() == b2.getS() ); // false
  System.out.println( b1.getS().equals( b2.getS() ) ); // true

How to override equals method
Now I have a Person class which has Name and Age as class variables.I want to override equals method so that I can check between 2 People objects.

public class Person 
{
private String name;
private int age;

public Person(String name, int age){
    this.name = name;
    this.age = age;
}

@Override
public boolean equals(Object obj) 
{
    if (obj == null) {
        return false;
    }

    if (!Person.class.isAssignableFrom(obj.getClass())) {
        return false;
    }

    final Person other = (Person) obj;

    if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
        return false;
    }

    if (this.age != other.age) {
        return false;
    }
    return true;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
    hash = 53 * hash + this.age;
    return hash;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

TestEquals.java

public class TestEquals
{
  public static void main(String[] args) 
  {  
    ArrayList<Person> people = new ArrayList<Person>();
    people.add(new Person("Mugil",30));
    people.add(new Person("Susan",23));
    people.add(new Person("Madhu",32));
    people.add(new Person("Monolisa",25));

    Person checkPerson = new Person();

    for (int i=0;i<people.size()-1;i++)
    {
            System.out.println("-- " + checkPerson.getName() + " - VS - " + people.get(i).getName());
            boolean check = people.get(i).equals(checkPerson);
            System.out.println(check);
    }
  }
}

You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals()