Monday, 11 May 2015

Java: Abstract Classes vs Interfaces

Interfaces & abstract classes:
--------------------------------------

=> Major difference:
* Abstract class are permitted to implement some methods while interfaces are not
* Abstract class have an constructor  and hence hold state,but Interface doesn't have an constructor so it doesn't hold the state .
*One of the major benefits of abstract classes is that you can reuse code without having to retype it
* To implement the type in an abstract class, a class must be a subclass of the abstract class
  while any class that defines all of the required methods is permitted to implement an interface, regardless of where the class resides in the class hierarchy.

=> Because Java permits only single inheritance, this restriction on abstract classes severely constrains their use as type definitions.

Some advantages of interfaces over abstract classes:
-----------------------------------------------------------------
*  Existing classes can be modified to implement a new interface
but not for abstract classes
 = suppose class A & B extend some abstract class D
 - now, if class A and B are modified to extend the same abstract class C, then C should also have to be made to extend a class D which is A & B's common ancestor
 - this is an issue as now we'll have to modify all sub-classes of D to extend C which may be inappropriate

* Interfaces allow the construction of non-hierarchical type frameworks

* A class can implement multiple interfaces but can extend only one class


public interface MyInterface
{
  void Execute();
}

VS

public abstract class MyAbstractClass
{
  public abstract void Execute();
}


Some advantages of abstract classes over interfaces:
--------------------------------------------------------------------

* It's far easier to evolve an abstract class than an interface
(coz when a new method has to be added, we can add it in abstract class and it's all exisiting implementations will provide the new method
but if we add one in interface, all implementation classes will have to implement it)

=> Hence, once an interface is released and widely implemented, it is almost impossible to change
   but java 8 on-wards  interface can be modified and one can add default method.


Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
         

java 8 on-wards  interface can be modified and one can add default method.    

The interfaces in java supports the multiple inheritance , then oblivious  question is what about the  Diamond Problem  ?. How to deal with it ? -- Its programmers job to deal with it.

public class MyClass implements InterfaceA, InterfaceB {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

    @Override
    public void saySomething() {
        System.out.println("Hello World");   //Still need to provide the Implementation  for method 
    }

}

interface InterfaceA {

    public void saySomething();

    default public void sayHi() {
        System.out.println("Hi from InterfaceA");
    }

}

interface InterfaceB {
     default public void sayHi() {
        System.out.println("Hi from InterfaceB");
    }
}

 If we want to specifically invoke one of the sayHi() methods in either InterfaceA or InterfaceB, we can also do as follows:

  @Override
    public void sayHi() {
       InterfaceA.super.sayHi();
    }

3 comments:


  1. Abstract class are permitted to implement some methods while interfaces are not
    Interface allows to write the method on-words java 8
    https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

    ReplyDelete
  2. default methods (i.e. methods with a default modifier) with implementation are allowed in interface from Java-8 onwards. Please visit the following link for details:
    http://java.dzone.com/articles/interface-default-methods-java

    ReplyDelete
  3. Difference between Default Method and Regular Method
    Default Method is different from the regular method in the sense that default method comes with default modifier. Additionally, methods in classes can use and modify method arguments as well as the fields of their class but default method on the other hand, can only access its arguments as interfaces do not have any state.

    In summary, Default methods enable to add new functionality to existing interfaces without breaking older implementation of these interfaces.

    When we extend an interface that contains a default method, we can perform following,

    Not override the default method and will inherit the default method.
    Override the default method similar to other methods we override in subclass..
    Redeclare default method as abstract, which force subclass to override it.

    ReplyDelete