In this tutorial I will show you how to create and work with Java Interfaces. As always I will demonstrate a practical example of Java interface.
What is Java Interface?
As many other Java concepts, Interfaces are derived from real-world scenarios with the main purpose to use an object by strict rules. For example, if you want to turn on the washing machine to wash your clothes you need to press the start button. This button is the interface between you and the electronics inside the washing machine. Java interfaces have same behaviour: they set strict rules on how to interact with objects. To find more about Java objects read this tutorial.
The Java interface represents a group of methods with empty bodies. Well, it is not mandatory to have a whole list of methods inside an interface – they can be 0 or more… but, no matter the number of methods, they all should be empty.
Create an Interface
Using the example with the washing machine, lets create an Interface called WashingMachine
with one method startButtonPressed()
public interface WashingMachine { public void startButtonPressed(); }
That’s all you need to define an interface. Note the usage of the keyword interface
. The method startButtonPressed()
has no body. It just ends with ; Of course you can also use methods with return types and parameters like: public int changeSpeed(int speed);
How to Implement an Interface
Now we will create a class that implements our interface. To continue with the example we will create a washing machine of specific make that has the start button.
public class SamsungWashingMachine implements WashingMachine { @Override public void startButtonPressed() { System.out.println("The Samsung washing machine is now running."); } }
We use the implements
keyword in the class declaration. We need to implement the startButtonPressed method (give it some functionality) or otherwise our class will not compile.
Please note, you can implement more than one interface in one class. You just need to separate the interface names with commas in the class declaration like this:
public class SamsungWashingMachine implements WashinMachine, Serializable, Comparable<WashinMachine> { ... }
Test your Interface
Now lets create a small program to test our interface and the implementation
public class Test { public static void main(String[] args) { WashinMachine samsungWashinMachine = new SamsungWashingMachine(); samsungWashinMachine.startButtonPressed(); } }
and the output of the program will be :
The Samsung washing machine is now running.
Use Interfaces to Declare Specific Object Characteristics
There is another common usage of interfaces in Java – to tell an object has specific use or characteristics.
Lets give one more real-world example. You are a survival in the woods. You find different objects and put them in your backpack for later use. When you rest you go through the found objects and eat the once that are eatable.
First, lets define an interface called FoundObject
with no methods at all. Those are all the objects we found in the woods:
public interface FoundObject { }
now we define a second interface called Eatable
. We will use it just to denote if the object is eatable or not
public interface Eatable { public void eat(); }
With the following three classes we will define the objects we find in the woods – apples, raspberries and stones
public class Apple implements FoundObject, Eatable { private String name; public Apple(String name) { this.name = name; } @Override public void eat() { System.out.println("Yummy! you eat some " + this.name); } }
public class Raspberry implements FoundObject, Eatable { private String name; public Raspberry(String name) { this.name = name; } @Override public void eat() { System.out.println("Yummy! you eat some " + this.name); } }
public class Stone implements FoundObject { private String name; public Stone(String name) { this.name = name; } }
Now lets write the survival program. We will collect found objects in our backpack (array) and try to eat them
public class WoodsSurvival { public static void main(String[] args) { // create an array of type FoundObject FoundObject backpack [] = new FoundObject[3]; // create the objects we found in the woods FoundObject apple = new Apple("apple"); FoundObject stone = new Stone("stone"); FoundObject raspberry = new Raspberry("raspberry"); // add the found objects to the backpack backpack[0] = apple; backpack[1] = stone; backpack[2] = raspberry; // iterate over the found objects for (int i=0; i<backpack.length; i++) { FoundObject currentObject = backpack[i]; // check if object is eatable if (currentObject instanceof Eatable) { // cast the object to eatable and execute eat method ((Eatable) currentObject).eat(); } } } }
The output of the program is:
Yummy! you eat some apple Yummy! you eat some raspberry
The code explained
First we create the interface FoundObject
with the sole purpose to denote the objects of specific type, so we can put them in the same array. We create the Eatable
interface to mark which objects can be eaten.
When we create the three objects (apple, raspberry and stone) we put implements FoundObject
in the class declaration for all of them, and the one we can eat also implement the Eatable
interface.
In WoodsSurvival
class we first create an array of type FoundObject
. The three object we create later are also of type FoundObject
so we can put them in the same array. Follow this article to learn more about Java arrays.
When we iterate the array we check if the current object is of type Eatable
. We do this with the help of instanceof
keyford. instanceof
returns true if two objects are of the same type. In our case apples and raspberries will return true when checked with instanceof Eatable
, because both implement the Eatable
interface. To be able to execute the eat()
method we need to explicitly typecast the object to Eatable
first. We achieve this with following line of code:
((Eatable) currentObject).eat();
We can not execute the eat method of a stone object, because it is not of type Eatable
.
Disclaimer
The code example above can be written in more fashionable way using abstract classes, Collections and inheritance. Some of those are more advanced topics and are explained in next tutorials. This is a beginner tutorial that intents to explain java interfaces only.
Thanks!
Its a good start. thanks for your post…