Saturday 25 August 2012

When should I use an interface instead of an abstract class?


Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.

Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts

Say a real estate builder is constructing an apartment with many flats.All the rooms in the flats have the same design,except the bedroom. The bedroom design is left for the ppl who would own the flats i.e; the bedRooms can be of different designs for different flats. 

I can achieve this through an abstract class like below:



public abstract class Flat
{
 //some properties


 public void livingRoom(){
    //some code
 }
 
 public void kitchen(){
    //some code
 }

 public abstract void bedRoom();

}

An implementation class would be as follows:
public class Flat101 extends Flat
{
        public void bedRoom() {
            System.out.println("This flat has a customized bedroom");
       }  

}

Suppose real estate builder is allowing you to customize all the rooms according to
your taste then you can go with interface.


interface Flat {
 // some properties

 public void livingRoom();

 public void kitchen();

 public void bedRoom();

}

public class Flat101 implements Flat {

 @Override
 public void livingRoom() {
  System.out.println("This flat has a customized living room");

 }

 @Override
 public void kitchen() {
  System.out.println("This flat has a customized kitchen");

 }

 @Override
 public void bedRoom() {
  System.out.println("This flat has a customized bedroom");

 }

}


One more thing is that interface supports multiple inheritance in Java i.e. you can implement more than one interface at a time or you can extend one class and implement one or more interfaces at the same time.

Interfaces can also be used as marker interface, interface with no methods in it.For example java.lang.Cloneable and java.io.Serializable.

2 comments: