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.