Thursday, December 4, 2014

Which should you use, abstract classes or interfaces?


  • Consider using abstract classes if any of these statements apply to your situation:

    • You want to share code among several closely related classes.

    • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

    • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

  • Consider using interfaces if any of these statements apply to your situation:

    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.

    • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.


    • You want to take advantage of multiple inheritance of type.


public interface Relatable {
        
    // this (object calling isLargerThan)
    // and other must be instances of 
    // the same class returns 1, 0, -1 
    // if this is greater than, 
    // equal to, or less than other
    public int isLargerThan(Relatable other);
}

-----------------------------------------------



public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else 
      return object2;
}



https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html