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

JavaOopInheritanceInterfaceAbstract Class

Java Problem Overview


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

Java Solutions


Solution 1 - Java

From Java How to Program about abstract classes:

> Because they’re used only as superclasses in inheritance hierarchies, > we refer to them as abstract superclasses. These classes cannot be > used to instantiate objects, because abstract classes are incomplete. > Subclasses must declare the “missing pieces” to become “concrete” classes, > from which you can instantiate objects. Otherwise, these subclasses, too, > will be abstract.

To answer your question "What is the reason to use interfaces?":

> An abstract class’s purpose is to provide an appropriate superclass > from which other classes can inherit and thus share a common design.

As opposed to an interface:

> An interface describes a set of methods that can be called on an > object, but does not provide concrete implementations for all the > methods... Once a class implements an interface, all objects of that class have > an is-a relationship with the interface type, and all objects of the > class are guaranteed to provide the functionality described by the > interface. This is true of all subclasses of that class as well.

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

Solution 2 - Java

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).

Solution 3 - Java

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; }
}

Solution 4 - Java

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

Solution 5 - Java

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:

https://stackoverflow.com/questions/18777989/how-should-i-have-explained-the-difference-between-an-interface-and-an-abstract/34978606#34978606

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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

Solution 13 - Java

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...

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

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.

Solution 17 - Java

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.

Solution 18 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaugmentie123View Question on Stackoverflow
Solution 1 - JavakgdesouzView Answer on Stackoverflow
Solution 2 - JavaKonstantin YovkovView Answer on Stackoverflow
Solution 3 - JavaDaniel W.View Answer on Stackoverflow
Solution 4 - JavaMadProgrammerView Answer on Stackoverflow
Solution 5 - JavaRavindra babuView Answer on Stackoverflow
Solution 6 - JavaAkash5288View Answer on Stackoverflow
Solution 7 - Javauser2768308View Answer on Stackoverflow
Solution 8 - JavafortytwoView Answer on Stackoverflow
Solution 9 - JavaArthur DentView Answer on Stackoverflow
Solution 10 - JavaDineshView Answer on Stackoverflow
Solution 11 - JavaHM NayemView Answer on Stackoverflow
Solution 12 - JavaWill JamiesonView Answer on Stackoverflow
Solution 13 - Javapraveen tyagiView Answer on Stackoverflow
Solution 14 - JavasridharView Answer on Stackoverflow
Solution 15 - Javakavi temreView Answer on Stackoverflow
Solution 16 - JavaRaghuView Answer on Stackoverflow
Solution 17 - JavaRavi SoniView Answer on Stackoverflow
Solution 18 - JavaJoshua KernView Answer on Stackoverflow