Java Interfaces
In this article, we will take a deep dive into java interfaces, what are these, how to define an interface, implement it with examples.
Abstraction means to display only required details while hiding the unnecessary or implementation information.
A simple example of abstraction is any machine such as a car.
A car
- consists of a key hole where you insert the car key, turn it and the car starts. What is happening behind is hidden from the user.
- has an accelerator. When it is pressed, the speed of car rises. How it is done, user does not know.
- has a brake. Driver knows that pressing it will reduce the speed of car, nothing else.
There are two methods of achieving abstraction in java: Abstract classes and interfaces.
What is an interface?
An interface is a contract that defines the behavior of a class. It is used to achieve abstraction in java.
A class implementing an interface is bound to provide definition of all the methods declared in the interface or else the class should be marked as abstract
.
Taking the car example mentioned above, an interface can be created with methods such as
1. startCar()
Method that defines the functionality when the key is turned.
2. pressAccelerator()
Method performing accelerator press function.
3. pressBrake()
Method containing brake press action code.
And the implementor class will define the code for above methods.
Prior to java 8 an interface could only contain method declarations and constants.
Method declaration means only the signature of a method and not its body.
In simple words, it could contain only abstract methods. Also, methods should be public
.
public
and abstract
even if you do not.But as a new feature in java 8, interfaces are allowed to contain method definitions(or body) also in the form of default methods and static methods.
Why use interface?
Following are the important uses of java interfaces
- As stated above, interfaces are used to achieve abstraction.
- Second and most important utility of an interface is to achieve multiple inheritance in java since java does not support it directly.
- Interfaces are also used to make the components of an application loosely coupled.
Loose coupling means little or no dependencies among components. Interfaces declare methods and classes provide their definition.
This means that the actual method implementations are not dependent on interfaces, thus loosely coupled.
Enough details about interfaces, now let us learn how to create an interface in java.
An interface is created using interface
keyword followed by the name of interface and then by curly braces.
These curly braces then include method declarations, constants or method bodies.
Example,
public interface Technology { // constant public String name = "java"; // method declaration public void printName(); }
Above code declares an interface named Technology with public
access modifier.
It has one field which is of type java.lang.String
and a method declaration.
Note that access specifier rules that apply to a class are also applicable to interfaces.
Few things that should be remembered regarding interface, its fields and methods are
- An interface is abstract by default. Compiler automatically applies abstract to the interface and its definition becomes
public abstract <interface name>
- Fields defined in an interface are
public
,static
andfinal
by default. Even if you do not write these before a field, the compiler applies it.
Thus, fields declared in the interface can be directly accessed using the name of interface just like static fields of a class.
Also, you cannot change their value after definition. - Methods defined in the interface are
public
andabstract
. You can not applyprivate
orprotected
access modifiers to them.
Even if you do not apply these, the compiler will do it for you.
Implement interface
Implementing an interface means providing definitions to all its abstract methods.
An interface is implemented by a class using implements
keyword followed by the name of the interface to be implemented.
Once a class declares that it will implement an interface, it needs to provide definition of all the methods in the interface.
If it does not provide implementations for all the methods or for only some of its methods, the class should be declared as abstract.
Example of a class implementing the above interface is given below.
public class CodippaImpl implments Codippa { public String printName() { System.out.print("codippa.com"); // access interface field System.out.print(Codippa.technology); } }
Interface program
Below is a simple interface program in java which creates an interface and a class that implements this interface.
public interface Laptop { public String getBrandName(); } // Interface implementor 1 public class Dell implements Laptop { // provide interface method implementation public String getBrandName(){ return "Dell"; } } // Interface implementor 2 public class Lenovo implement Laptop { // provide interface method implementation public String getBrandName(){ return "Laptop"; } } public class InterfaceExample { public static void main(String[] a) { // create object of Dell class Dell dell = new Dell(); String dellBrand = dell.getBrandName(); System.out.println(dellBrand); // create object of Lenovo class Lenovo lenovo = new Lenovo(); String lenovoBrand = lenovo.getBrandName(); System.out.println(lenovoBrand); } }
Above code creates two implementation classes for the interface, creates their objects and calls the interface method that these classes implement.
Output is
Dell
Lenovo
Multiple inheritance using interface
Multiple inheritance means creating child class that has more than one parent classes.
Java does not support multiple inheritance.
That is, a class cannot have more than one parent class.
But multiple inheritance can be achieved using interfaces. This is because there is no restriction on the number of interfaces a class can implement.
A class can extend another class and implement an interface at the same time.
If a class does this, then extends
is written first and then implements
.
Thus, below syntax is valid
public class A extends Parent implements InterfaceAlso
A class can implement more than one interfaces as shown below.
public interface One{ // method declaration } public interface Two { // method declaration } public class Implementor implements One, Two { // method definitions of both interfaces }
A class can implement any number of interfaces by providing the names of those interfaces after implements
separated by comma.
Similar to classes, interfaces in java can also have parent-child relationship among them.
That is, an interface can extend another interface using
extends
.
Interface before extends
is the child interface while after extends is the parent interface.
All the methods and fields of the parent interface are inherited in the child interface as well.
Example,
public interface Animal { public void getCategory(); } public interface Carnivore extends Animal { public void getName(); }
Number of methods in Carnivore
interface will be getCategory
and getName
.
If a class implements Animal
interface, then it needs to provide definition of getCategory
method.
If a class implements Carnivore
interface, then it will have to provide definition of getCategory
and getName
methods.
An interface can only extend another interface, it cannot implement some other interface.
That is, you can NEVER write interface implements interface.
Java Native interfaces
Java language itself defines many interfaces. Some of them are
1. java.lang.Comparable
2. java.lang.Comparator
3. java.util.Iterator
4. java.io.Serializable
5. java.util.Collection
, and many more…