[java] When do I have to use interfaces instead of abstract classes?

I was wondering when I should use interfaces.

Lets think about the following:

public abstract class Vehicle {
   abstract float getSpeed();
}

and :

public interface IVehicle {
  float getSpeed();
}

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

What is the reason to use interfaces?

Thanks!

EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

This question is related to java oop inheritance interface abstract-class

The answer is


If you are using JDK 8, there is no reason to use abstract classes because whatever we do with abstract classes we can now do it with interfaces because of default methods. If you use abstract class you have to extend it and there is a restriction that you can extends only once. But if you use interface you can implements as many as you want.

Interface is by default an abstract class an all methods and constructors are public.


This is an direct excerpt from the excellent book 'Thinking in Java' by Bruce Eckel.

[..] Should you use an interface or an abstract class?

Well, an interface gives you the benefits of an abstract class and the benefits of an interface, so if it’s possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes.

In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change to an abstract class.


interface is basically used when two parties works together,and one party want to hide something from other(or only want to show some part of his class).than we use interface eg. in jdbc jdbc vendors provide us some interfaces bcoz they want to hide everything from us.

abstract class is only used in that case when we want to support a common behavior in more than one classes...or want to provide some preimplemented implementation with some unimplemented methods(methods should be abstract). eg. http servlet in servlet interface is an abstract class bcoz this class implements servlet interface except it's service method...so this class help us to get some preimplemetation of interface method...


From the Oracle tutorials :

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).


With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

Have a look at oracle documentation too to understand the differences in better way.

Have a look at this related SE questions with code example to understand things in better way:

How should I have explained the difference between an Interface and an Abstract class?


Considering Java:

Interfaces:

  • Are a fundamental OOP abstraction.
  • Will often (but not always) yield clearer code than abstract classes.
  • Can be implemented by multiple concrete classes to suit different situations.
  • Can directly implement scenarios calling for multiple inheritance.
  • Can be more easily mocked out for testing purposes.
  • Are useful for JDK proxies (see java.lang.reflect.Proxy).

These are just the beginning of a very long list of pros/cons for interfaces vs. abstract classes.


There are a number of times you might consider using an interface over an abstract implementation

  • When the available abstract implementation doesn't do what you want and you want to create your own
  • when you have an existing class (that extends from other class) and you want to implement the functionality of the interface

Generally speaking, interfaces were introduced to overcome the lack of multiple inheritancy, amongst other things


Abstract classes can contain methods that are not abstract, whereas in interfaces all your methods are abstract and have to be implemented.

You should use interfaces instead when you know you will always implement those certain methods. Also you can inherit from multiple interfaces, it is java's way of dealing with multiple inheritance


Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

Interface : It define just protocol which all subclass need to follow.


From The Java™ Tutorials - Abstract Classes Compared to Interfaces

Which should you use, abstract classes or interfaces?

  • Consider using abstract classes if any of these statements apply to your situation:
    • You want to share code 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:
    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    • You want to 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.

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.


Interfaces and abstracted classes seem very similar, however, there are important differences between them.

Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.

Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:

public abstract class Car{
    private String make;
    private String model

    protected Car() { }  // Default constructor

    protect Car(String make, String model){
        //Assign values to 
    }

    public abstract void howToStart();
}

Then with the Honda class we would have:

public class Honda extends implements Engine {

    public Honda() { }  // Default constructor

    public Honda(String make, String model){
        //Assign values
    }

    @Override
    public static void howToStart(){
        // Code on how to start
    }

}

Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine.

For the engine interface we could create:

public interface Engine {
    public void startup();
}

The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup(); method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:

public class Honda extends implements Engine, Transmission, List<Parts>

Hopefully this helps.


Actually Interface and abstract class are used to just specify some contract/rules which will just show, how their sub classes will be.

Mostly we know that interface is a pure abstract.Means there you cant specify a single method with body.This particular point is the advantages of abstract class.Means in abstract class u have right to specify method with body and without body as-well.

So if u want to specify something about ur subclass, then u may go for interface. But if u also want to specify something for ur sub classes and u want also ur class should also have some own method.Then in that case u may go for abstract class


Many cases can be implemented in both class types.

Interfaces are usefull when you want to define a class that has to have at least basic functions. Like a real interface for example USB.

interface USB {
    public function sendPower(); //charge iphone for example
    public function sendData(); //itunes
    public function recieveData();
}

Use abstract classes when there are several ways to to implement an object.

abstract class MobilePhone {
    public function isIphone();

    public function charge() {
        //get some power, all phones need that
    }
}

class iPhone extends MobilePhone {
    public function isIphone() { return true; }
}

You can't achieve multiple inheritance with abstract class, that is why Sun Microsystems provide interfaces.

You cannot extend two classes but you can implement multiple interfaces.


Use an abstract class when you want to define a template for a group of sub-classes , and you have at least some implementation code that call sub-classes could use.

Use an interface when you want to define the role that other classes can play, regardless of where those classes are in the inheritance tree

you extend an abstract class

you implement an interface :)

in an interface all the fields are automatically public static final and all the methods are public whereas an abstract class allows you a bit of flexibility here.


The answer of this question is very simple,Whatever we can do with interface can be done with abstract class Agree...so when to use interfaces,the answer lies in C# restriction of multiple inheritance. When you have only contracts(abstracts) to declare and want your sub-classes implement it go with interfaces, because if you use abstract class in this case, you can not inherit from one more class and you are stuck if want to inherit from one more class,but you can implement as many interfaces.


Interface and Abstract Class are the two different ways to achieve Abstraction in OOP Languages.

Interface provides 100% abstraction, i.e all methods are abstract.

Abstract class provides 0 to 100% abstraction, i.e it may have or may not have abstract methods.

We can use Interface when we want all the functionality of a type to be implemented by the client.

We can use Abstract Class when some common functionality can be provided by Abstract Class implementer and client will be given chance to implement what he needs actually.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to inheritance

How to extend / inherit components? Inheritance with base class constructor with parameters Class is not abstract and does not override abstract method Why not inherit from List<T>? Can an interface extend multiple interfaces in Java? How to call Base Class's __init__ method from the child class? How should I have explained the difference between an Interface and an Abstract class? JavaScript OOP in NodeJS: how? When do I have to use interfaces instead of abstract classes? C++ calling base class constructors

Examples related to interface

Cast object to interface in TypeScript When to use Interface and Model in TypeScript / Angular Is there a way to create interfaces in ES6 / Node 4? Can a normal Class implement multiple interfaces? When to use: Java 8+ interface default method, vs. abstract method How should I have explained the difference between an Interface and an Abstract class? When do I have to use interfaces instead of abstract classes? How to extend a class in python? Interface type check with Typescript Abstract Class vs Interface in C++

Examples related to abstract-class

invalid new-expression of abstract class type Class is not abstract and does not override abstract method When to use: Java 8+ interface default method, vs. abstract method Spring can you autowire inside an abstract class? Abstract Class:-Real Time Example How should I have explained the difference between an Interface and an Abstract class? When do I have to use interfaces instead of abstract classes? Is it possible to make abstract classes in Python? Abstract Class vs Interface in C++ How do you handle a "cannot instantiate abstract class" error in C++?