Interfaces
The interface is one of the core concepts used in Java OOPS, so it's necessary for us to familiarize ourselves with interfaces and their use.
Interfaces are similar to classes. The only difference between an interface and a class is that an interface will have methods but not a body. Confused? In a class, we generally define a method and then start writing code into it. For example, in a class, if we want to write any code, we just start off by declaring the class using public void
and proceed with the rest of the code in that class, as follows:
public void getData() { }
In interfaces, we can only define the signature of the method; we cannot write any code inside the method. But why? What is the use of writing a method signature inside an interface? What is the use of this object-oriented concept in Java? You might have these questions in your mind, so let's try to understand the concept of the interface with a real-life scenario.
Using interfaces with a traffic light system
Consider...