Abstract class Vs Interface

Difference between abstract class and interface

To understand difference between abstract class and interface, first, we have to understand what is an abstract class and an interface and what are the similarities.

Abstract class in plain terms is a class which contains one more abstract methods. Abstract method has no implementation, just a declaration. Sub-classes of abstract class are responsible for providing implementation of such methods. Example of an abstract class as follows

package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public abstract class AbstractBicycle {
    //member fields
    protected int gears;
    protected int topSpeed;
    protected int serviceCost;

    public int getGears(){
        return this.gears;
    }

    public abstract void service();
}

 

On the other hand, interfaces are like contracts which are honored by every class which implements them. It does not matter how a class implement the contract, as far as it implements it. For example, Television box can have may functionalities like changing channels, volume control, records, selection of source etc. TV manufacturers defined this industry standard interfaces, so that remotes can be build to call these behaviors on TV sets. It does not matter how different models of TV implement these interface, as far as they implement it.

Interface is again just like a class, which contains all abstract methods.  Implementation of those methods is left to class  which implements interface. Interface can contain constants too which are by default final. Example of declaration of an interface be

package Examples;

/**
 * Created by sangar on 22.10.17.
 */
interface IBicycle {

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

So, what’s the difference between abstract class and interface then? There are very subtle differences as follows

  1. Abstract class is object oriented in nature as it defines hierarchy between classes, on the other hand interfaces are functional in nature as they define what a class has to implement to satisfy this interface.
  2. Methods and fields in abstract class can have individual access specifiers like private, public or protected, where as in interfaces, everything has to be public. Sub-class implementing abstract methods from abstract class can keep visibility same or reduce it, whereas class implementing interface has to keep visibility same which is public.
  3. A sub-class or child can only extend single abstract class, whereas a class can implement multiple interfaces.
  4. By definition, abstract class can have default implementation of some methods, where as interface just has definition of all methods. This is not true from Java 8 default method signatures in interface. Refer here for more details.
  5. Sub-class uses extends to use abstract class where implements to implement an interface.
  6. Abstract classes can have constructors but interfaces can’t have constructors.

Abstract class Vs Interface : When to use what?

Now, when to use what? When to use abstract class and when to go to interfaces.

Consider using abstract classes if any of these statements apply to your situation:

  • You want to share implementation among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:

  •  If unrelated classes would implement your interface.
  • Specify the behavior of a particular data type, but not concerned about who  implements its behavior.
  • You want to take advantage of multiple inheritance of type.

Reference : Oracle documentation

In short, abstract class provides is-a kind of relationship between class and concrete sub-classes whereas interface provides has-a capability between unrelated classes.

This post clarifies difference between abstract class and interface and explains when to use what. Hope it helped you!

Please share if there is something wrong or missing. If you want to contribute to website, please reach out to us through contact form or drop a mail to jitsceait@gmail.com.

 

Object oriented programming : Classes

What is a class?

In object oriented programming parlance, a class is a blue print used to create different instances, called objects, of a domain entity. Classes encapsulate state and behavior of domain entity.  State is maintained using member variables and behavior using member functions.

For example, Bicycle is a class, it has three members : model name, top speed and number of gears. Based on this blueprint, we can instantiate objects like bike with 2 gears and 15 as top speed, another bike with 6 gears and 20 as top speed etc. Behaviors like change the top speed, get the number of gears are all encapsulate with in class and available in all instances of class Bicycle.

/**
 * Created by sangar on 22.10.17.
 *
 */
package Examples;
public class Bicycle {
    
    private int gears;
    private int topSpeed;
    
    public Bicycle(int gears, int topSpeed){
        this.gears = gears;
        this.topSpeed = topSpeed;
    }
    
    public int getGears(){
        return this.gears;
    }
    
    public void service(){
        System.out.println("Servicing for bike with grear"
           + this.gears + "costs $10");
    }
}

Are all classes used to create objects? Answer is no, as there are abstract classes and static classes, which cannot be instantiated as usual classes.

An abstract class contains one or more abstract methods. Abstract method does not have implementation, it only has declaration. An abstract class requires subclass to provide implementation of methods and instantiate it.

Continuing above example of bicycle, it would be nice if we can define different types of bicycles like city bikes, mountain bikes and racing bikes. All these bikes will have some common behavior like service, but the implementation of that behavior would be different for each one it. In this scenario, Bicycle becomes an abstract class and declares member function without implementation. City bike,  Mountain bike and Racing bike are sub-classes of bicycle abstract class and implement the service method.

package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public abstract class AbstractBicycle {
    //member fields
    protected int gears;
    protected int topSpeed;
    protected int serviceCost;

    public int getGears(){
        return this.gears;
    }

    public abstract void service();
}
package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public class MountainBike extends AbstractBicycle {

    public MountainBike(int gear,
                        int topSpeed, int serviceCost){
        this.gears = gears;
        this.topSpeed = topSpeed;
        this.serviceCost = serviceCost;
    }

    public void service() {
        System.out.println("Servicing Mountain Bike :");
        System.out.println("Oil the chain");
        System.out.println("Check tyre pressure");
        System.out.println("Oil brake");
    }
}
package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public class CityBike extends AbstractBicycle {
    public CityBike(int gear,
                    int topSpeed, int serviceCost){
        this.gears = gears;
        this.topSpeed = topSpeed;
        this.serviceCost = serviceCost;
    }

    public void service() {
        System.out.println("Servicing City Bike :");
        System.out.println("Oil the chain");
        System.out.println("Fix the lock");
    }
}
package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public class BicycleStore {

    public static void main(String[] args){
        MountainBike mountainBike = new MountainBike(3,15,7);
        mountainBike.service();

        CityBike cityBike = new CityBike(6,10,10);
        cityBike.service();
    }
}

On the other hand, static class is a class, which is never required to be instantiated. It contains member values which will not differ across instance and methods, which do not depend on external context.  In Java specifically, nested classes are static in nature.

What does a class contain?

As mentioned above, a class will contain member fields and functions. A class can also have one or more constructors.

Member fields can be public, private or protected. In short, public members can be access from outside of the class, using objects. Private members are not visible outside of class and can only be accessed by member functions of class itself. Protected ones have different rules when it comes to inheritance, but usually, accessible from within package, subclass and not accessible to outside world.

Access control specifier in Java

One can have setters and getters on fields of class. Setters set the value of fields and getters retrieve value of fields.

We will be discussing more advance things in following posts, so please stay tuned. Also, if you find anything wrong or missing, please let us know. We would be more than happy to correct things.