Understanding Interfaces
Interfaces are abstract classes. We don’t usually put the abstract keyword at the class or method levels of interfaces because the compiler is smart enough to know that we are referring to abstraction when dealing with interfaces.
- All fields and methods of an interface are implicitly public.
- All fields are public static. The reason why all fields must be final is because we are making a true contract with whoever will be implementing the contract. For example, when a client implements an interface we are making a guarantee that the value of the fields will not change. If they did then the client would be required to change their code as well, resulting in a tightly coupled design (Which we tried to avoid when possible )
- As of Java 8, we can declare default methods with the interface.
- Another quick note: Interfaces can extend other interfaces. And in turn become sub-interfaces.
Interfaces, allows us to re-use code and extend are applications very easily. Also, allows us to achieve inheritance and polymorphism within are applications. An interface is what is sounds like. The users of our application will “interface” with our application through the interfaces we define.
An interface specifies what a class must adhere to. Any class that implements an interface must adhere to the ‘contract’ created by the interface. Kind of like a blueprint to the implementation class. Please take a look at the interface declared below and notice the keyword interface. All methods of an interface must be abstract, meaning they will not have a body. Also, any variables declared in an interface must be declared with the keyword final.
public interface Vehicle {
public void drive();
default void description() {
System.out.println("I am a vehicle");
}
} public class Car implements Vehicle {
@Override
public void drive(){
description();
System.out.println("Car is driving");
}
public static void main(String args[]){
Car car = new Car();
car.drive();}
}
Above we have the Car class implementing the Vehicle interface. Since the Car class implements the Vehicle class. The car class will add the method definition for the drive() method.