Wednesday, May 14, 2008

Difference between Interfaces and Abstract Classes


We’ll first discuss what Interfaces and Abstract Classes are all about to understand the differences between the two more clearly and completely.

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(){
……
}
}

Difference between Interfaces and Abstract Classes: From the language perspective, there are several differences, few of them are:-

  • An abstract class may contain fields, which are not ‘static’ and ‘final’ as is the case with interfaces.
  • It may have few (or all) implemented methods as well, whereas Interfaces can’t have any implementation code. All the methods of an interface are by default ‘abstract’. Methods/Members of an abstract class may have any visibility: public, protected, private, none (package). But, those of an interface can have only one type of visibility: public.
  • An abstract class automatically inherits the Object class and thereby includes methods like clone(), equals(), etc. There is no such thing with an interface. Likewise, an abstract class can have a constructor, but an interface can’t have one…
  • Another very famous difference is that Interfaces are used to implement multiple inheritance in Java as a class in Java can explicitly have only one super class, but it can implement any number of interfaces… blah blah… :-)

From the performance perspective, the different is that Interfaces may be little slower as they require extra indirection to find the corresponding method in the actual class. Though, modern JVMs have already made that difference very little.

If you want to add a new method to an interface, then you either need to track all the classes implementing that interface or you’ll extend that interface to make a new interface having that extra method(s). In case of an abstract class, you’ll simply add the default implementation of that method and all the code will continue to work.

Many differences are listed already, but the main difference lies in the usage of the two. They are not rivals, but in most of the cases they are complimentary. We need to understand when to use what.

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.


Update[June 25, 2008]: Do interfaces in Java really inherit the Object class? If NOT then how do we manage to call Object methods on the references of an interface type? Read more in this article - Do Interfaces inherit the Object class in Java?


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


12 comments:

Anonymous said...

What a detailed explanation! Good work. A common que but never seen such an answer.

Anonymous said...

Good article!

One minor thing though: Interfaces do of course inherit all methods from Object. Everything in Java inherits from Object. Try it out in Eclipse or whatever IDE you prefer. You're able to call Object's methods on every reference of an interface type.

Martin

Geek said...

Thanks for your feedback Martin!

I think, an Interface can't inherit from a Class in Java.[i] "Everything in Java inherits from Object" (taken from your feedback) [/i]should actually be "Every Class in Java inherits from Object".

We can surely call Object methods on a reference of an interface type as to have a valid assignment to that reference type in Java, one needs to have an instance of the implementing class getting assigned to it. Now, the reference points to an object of an implementing class and that class will automatically inherit from the cosmic super class 'Object'.

interface SampleInterface{
...
}

class SampleClass implements SampleInterface{
/*... implementing the methods of the interface and other stuff...*/
...
}

public class SampleClassDemo {
public static void main(String [] args){
...
SampleInterface sampleInterface = new SampleClass();
...

/*...now we can call Object methods on the reference type SampleInterface as it actually points to an object of type SampleClass, which being a class automatically inherits from Object ...*/
....
}
}


Hope this helps.

Anonymous said...

Hey geek, I understand what you're saying, but I'm still in doubt... forgive me ;)

At compile time it is not known which implementing class will be assigned to a reference of an interface type (or a class type). The actual class is determined at runtime as you'll surely know. Thus all methods that are allowed to be called on a reference type are those methods that are defined for that reference type. Of course you might argue that since interfaces would not work without implementations the compiler is clever enough to know that these implementing classes will inherit Object's methods. Thus it could just allow those methods to be called on a reference of an interface type. However, I don't think that the compiler "thinks" that way. I think that interfaces really do inherit from Object as well.

Unfortunately I can't proof this, but I rembember (at least I think I do) that I read about that somewhere. I'm going to try to find this reference. Hope I'm able to find it. I really want to know now ;)

Cheers, Martin

Geek said...

Thanks Martin for being so active. You brought up an excellent point and I hope it'll help all of us in some way or the other.

I still re-iterate the same thing that Interfaces don't really inherit the Object class. They are actually implemented in a different way altogether to facilitate access to the Object methods (only public instance methods).

The Java Language Specification clearly says that the members of an interface are those which are declared in the interface and those which are inherited from direct super-interfaces. If an interface has no direct superinterface then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in the Object class, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by that interface. This is what makes the signatures of the Object methods available to the compiler and the code compiles without any error. Remember if the interface tries to declare a public instance method declared 'final' in the Object class then it'll result into a compile-time error.

But, this is not inheritance of Object class by an interface. Read more in the Update section of this article OR simply go to the following URL:-

http://geekexplains.blogspot.com/2008/06/do-interfaces-really-inherit-from-class.html

Hope this article helps. Please let me know in case you still have any doubts in this regard. Keep visiting/posting/contributing!

Anonymous said...

Hello geek,

I've read your article. Thank you for explaining that issue in such a detail. I really didn't know that. I've always thought that interfaces inherit from Object as well. I'm still sure that I read about that somewhere, but now I'm also pretty much sure that it was just incorrect. And now that you mentioned it... I've never really noticed that I don't have a clone() or finalize() method available on a reference type of an interface type. Wow ;) That makes it quite clear that interfaces don't inherit from Object as normal classes do. Interesting!

Thanks again for all your explanations. Keep it up!

Cheers, Martin

priyanka said...

Good one.Nice explanation

priyanka said...

Good one.nice explanation

Anonymous said...

Another difference between abstract class and interface in Java is that abstract class are slightly faster than interface in Java because of search and call is involve with interface method.

Anonymous said...

Thanks so much Geek! This article helped me understand this concept much better and this one helped as well: Interface vs Abstract class

Anonymous said...

Thanks so much Geek! This article helped me understand this concept much better and this one helped as well: Interface vs Abstract class

Java Experience said...

Another difference I would like to add is that while abstract classes allow constructors to be added, interfaces don't allow constructors.
See:
Abstract class and interface