Abstract Class versus Interface In Java

49 Flares Twitter 4 Facebook 9 Google+ 36 Pin It Share 0 LinkedIn 0 Filament.io 49 Flares ×

Introduction

In this article I will explore abstract class versus interfaces in java. There is a lot of confusion among beginners whether to use an abstract class or an interface in a given situation. The article looks deeper into the theoretical aspects supported by easy to understand code examples.

The Problem

An Abstract class with just abstract methods looks  a lot similar to an interface. In such a scenario is it better to use an interface ? That is a question often asked by many developers. Before going into the differences and similarities, let us first explore each of these elements one by one.

Abstract Class

An abstract class is a class that is declared abstract.  It is not mandatory for an abstract class to contain abstract methods. Abstracts methods are methods that are declared as abstract. An abstract method is just like a method declared in an interface – it cannot contain a body (without braces, and followed by a semicolon).

abstract void hello();

If the class includes any abstract method, the class should be declared as abstract.

Another important restriction is that an abstract class cannot be instantiated. You can only instantiate its sub class. This restriction is the most important aspect that makes an abstract class useful. Hence an abstract class is typically used in situations where you want to enforce something in the sub-classes. An important point to note – An abstract class can contain non abstract methods i.e it can contain method implementations along with methods declared as abstract. For instance

public abstract class HelloAbstract {

abstract void hello();

void printHello(String s) {
System.out.println(s);
 }
}

This is a very important feature of an abstract class and this feature makes it an important component in Object Oriented Design. Framework codes and algorithms greatly use abstract class because of this feature. Let us look at an example to understand the usefulness of abstract class.

Abstract class 


public abstract class Noodle {

final void makeNoodle(){

 boilWater();
 addNoodles();
 addTasteMaker();
 cook();
 }

 final void boilWater(){
 System.out.println("Boiling water");
 }

 final void addNoodles(){
 System.out.println("Noodles added to water");
 }

 abstract void addTasteMaker();
 abstract void cook();
}

 

Implementations

public class VegNoodles extends Noodle {

@Override
 void addTasteMaker() {
 System.out.println("adding VEG taste maker");

 }

@Override
 void cook() {
 System.out.println("Cooking for 4 minutes");

 }

}

 

public class ChickenNoodles extends Noodle {

@Override
 void addTasteMaker() {
 System.out.println("adding chicken taste maker");

 }

@Override
 void cook() {
 System.out.println("cooking for 5 minutes");

 }

}

The Noodle class defines the algorithm for making a noodle and it defines the order and provides implementations for a few steps. The sub classes are allowed to provide implementations for a few steps in the algorithm.But they cannot change the order of the steps nor change certain default behaviors ( they have to use the boilWater and addNoodles implementation provided by the abstract class).

Thus Noodle making process remains the same but the algorithm offers the flexibility to change the taste maker and cooking time. This is the beauty of an abstract class and this kind of behavior cannot be achieved using an Interface.

Interface

Interface is defined using the keyword interface .Interface cannot contain any method implementation and can only contain declarations. By default, the methods declared in an interface is public. By using an interface, you can enforce method contracts thereby letting you change the underlying implementation with out the need for the client or the caller to change.  Let us make this concept clearer using an example.

Example

public interface TV {

void play();
 void stop();
}

 Implementations


public class ColorTV implements TV {

@Override
 public void play() {
 // Do color TV Specific logic

 }

@Override
 public void stop() {
 // Do color TV Specific logic

 }

}

 

public class BlackAndWhiteTV implements TV {

@Override
 public void play() {
 // Black and white TV Specific Logic

 }

@Override
 public void stop() {
 // Black and white TV Specific Logic

 }

}

We have defined the service contract ( method signatures) in the interface (TV) and the concrete implementation classes ColorTV and BlackAndWhiteTV implements this contract. If  the client class programs to the TV interface and not to any concrete implementation, the TV can be switched from Color to BlackAndWhite or vice verse and there is no change to the client. The below code shows this

public class TestInterface {

/**
 * @param args
 */
 public static void main(String[] args) {

 TV tv=getTV();
 tv.play();
 tv.stop();

}
 public static TV getTV(){
 TV tv=new BlackAndWhiteTV();
 return tv;
 }

}

The code inside the main method that invokes the play and stop functions is not aware of whether it is a ColorTV or BlackAndWhiteTV. This is where interfaces are useful – to enforce service contract and let us you substitute the underlying implementation.

Summary – Abstract class versus Interface

  • Abstract classes are useful if you want to provide implementations to few methods and let sub classes to provide implementations to few others. Abstract classes are excellent candidates inside application frameworks.
  • Interfaces are useful when you want to specify the signature of a particular method, but not concerned about who implements its behavior.
  • If all the methods of an abstract class are uncompleted then it is same as an interface.
  • A class can implement any number of interfaces but can only sub class or extend a single class
  • All fields in an interface are by default public, static and final and all method declarations public by default
  • With abstract classes, you can declare fields that are not static and final.

Share this post:

Recent Posts

  • Hannes Steffenhagen

    IMHO, if the question “should this be an abstract class or an interface” comes up, the answer is “interface”. Period. Inheritance is a blunt instrument and should be used with appropitiate caution, reusing implementations is usually best done through composition rather than inheritance (in fact, interfaces + composition can be used in any situation you’d use an abstract class for, with little to no additional cost).

    That said, I kinda agree that abstract classes do have some place in frameworks.

    • http://pickadvice.com/ prem kumar

      I agree with you. Prefer interface and composition over inheritance. If you are coding an algorithm and want the sub classes to provide some steps then there is nothing better than an abstract class. Again, prefer composition over inheritance.

  • Ilyas

    This explanation of interface is now obsolete after java 8

  • Developers Lane

    DevelopersLane is a weblog devoted to uncovering the latest tools, resources, inspirational and motivational designs to help designers and developers turn their passion into profession with ease.