Difference Between Interface and Abstract Class

Difference Between Interface and Abstract Class


Interface: Java Interfaces are equivalent to protocols. They basically represent an agreed-upon behavior to facilitate interaction between unrelated objects. For example, the buttons on a Remote Controller form the interface for outside world to interact with TV. How this interface is implemented by different vendors is not specified and you’re hardly aware of or bothered about how these buttons have been implemented to work internally. Interface is plainly a contract between the producer and the consumer. How the producer implements the exposed behavior is normally not cared by the consumer.

In Java, an Interface is normally a group of methods with empty bodies. You can have constant declarations in a Java Interface as well. A class that implements the interface agrees to the exposed behavior by implementing all the methods of the interface.
interface TVRemoteController{
void power();
void setChannel(int channelNumber);
void upChannel();
void downChannel();
void upVolume();
void downVolume();
……
}

A sample implementation of this interface by a vendor, say Sony:
public class SonyTVRemoteController implements TVRemoteController{
/*…this class can have other methods, properties as well …*/
……
void power(){
//implementation of power() method of the interface
}
void setChannel(int channelNumber){
//implementation of setChannel(int) method of the interface
}
//similarly, implementation of other methods of the interface
……
}

Implementing an interface means the class will support at least the exposed behavior. It can definitely add any number of extra behaviors/properties for its clients. That’s why few Remote Controllers have hell lot of buttons :-)
Abstract Class: In Java, abstract class is a class which has been declared ‘abstract’. By declaring ‘abstract’ we ensure that the class can’t be instantiated. Why to have such a class then? Because, you would not be having implementation of all the methods in that class and you need to leave it to the subclass to decide how to implement them. In this case, there is no point instantiating an incomplete class.

An abstract method is a method which doesn’t have any implementation. If a class has even a single abstract method, then you got to declare the class ‘abstract’. Though, you don’t need to have at least one abstract method to declare a class abstract. You can declare a complete class as ‘
abstract’ as well. This practice is seldom used. One possible reason may be that you never want your clients to instantiate your class directly even though you’ve already provided default implementation of all the methods. Strange! Yeah… it is. The designer of such a class may like to provide the default implementation of at least one method just to serve as a template (and not the actual implementation) for the client and thus making the class incomplete. So, a client first needs to subclass and implement the method(s) by overriding them. Now the subclass will be a concrete/complete class. Does it make some sense? Okay… Let me try to give another example. Think of a hypothetical situation, where you need to design a class, which will have ‘n’ methods and ‘n’ clients, where every single client wants default implementation of ‘n-1’ methods and it needs to implement only one (unique to every client) of the methods. In such a situation, you may not like to declare any of the methods ‘abstract’ as it’ll be required to be a non-complete method only for one of the clients and a complete implementation for other ‘n-1’ clients. If you declare it ‘abstract’ then every client will need to implement it and you’ll end up getting ‘n-1’ same piece of code. On the other hand, if you don’t declare ‘abstract’ then you simply need to override this method in corresponding sub class. Since, the base class is incomplete in all the ‘n’ cases. Assuming that this class will have only these many forms of usage, you’ll never require having an instance of it. That’s why you would declare it ‘abstract’. Confused? Read this paragraph once more :-)
public abstract class SampleAbstractClass{
//…fields
……
//…non-abstract methods, if any
……
//…abstract method, if any J
abstract void sampleAbstractMethod(); //… ends with ‘;’
}

public class SubClassOfSampleAbstractClass extends SampleAbstractClass{
//… fields, and non-abstract methods (if any)
……
//…implementation of the abstract method
void sampleAbstractMethod(){
……
}
}


Feature
Interface
Abstract class
Multiple inheritance
class may inherit several interfaces.
class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovableinterface.
An abstract class defines the core identity of aclass and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstractclass is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of theinterface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined ininterfaces
An abstract class can have fields and constrants defined

When to use an Interface: it asks you to start everything from scratch. You need to provide implementation of all the methods. So, you should use it to define the contract, which you’re unsure of how the different vendors/producers will implement. So, you can say that Interfaces can be used to enforce certain standards.

When to use an Abstract Class: it is used mostly when you’ve partial implementation ready with you, but not the complete. So, you may declare the incomplete methods as ‘abstract’ and leave it to the clients to implement it the way they actually want. Not all the details can be concrete at the base class level or different clients may like to implement the method differently.

When to use both: if you want to implement multiple inheritance where you have the luxury of providing partial implementation as well. You’ll then put all that code in an abstract class (this can be a concrete class as well… but here we assume that the class is also only partially implemented and hence an abstract class), extend that class, and implement as may interfaces as you want.

Comments

  1. nice post and it helped me to understand clearly when to use abstract class and when to use interface.

    can u weite something about abstraction,info hiding and encapsulation.

    ReplyDelete
  2. abstraction,info hiding and encapsulation: I hope this post will help you....please check the 29th June 2012 post for your realated concepts.....

    Thanks for reading my blogger...for my reference i created this blog but it is helping others also ...am happy by seeing this comment

    ReplyDelete
  3. good explanation, thanks

    ReplyDelete
  4. advantages and disadvantages of Java Sockets Java Online Course direct program messages Java EE Training explicit object casting is needed Java Interview Questions variable having a supeclass type Java Training Institutes ifference between J2SDK 1.5 and J2SDK 5.0 IT Technical Articles

    ReplyDelete

Post a Comment

Please post comments here:-)

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Core Java -----Question and Answers