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
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.
Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc
Methods in interface are public or public static but methods in abstract class can be private and protected too
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:
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
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
andCloneable
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 includeHashMap
,TreeMap
, andConcurrentHashMap
) share many methods (includingget
,put
,isEmpty
,containsKey
, andcontainsValue
) thatAbstractMap
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.
Source: Stackoverflow.com