Interface is an abstraction class. Abstraction is the process of showing only the neccessary funtionality and hide the uncessary details.
What is an interface in Java?
An interface can have method signatures, default methods, and variables which are public, static, and final by default.
What is the use of an interface?
In java a class can only inherit a one other class. If you want to inherit two or more classes you need to use interfaces. A class can implement more than one interface.
How to create an interface?
1. Use the interface keyword. It looks like a class but it is not a class.
2. Use method signature only(implementation is hidden in the class that implements the interface).
interface UserAction{ // by default limit is public static final int = 10; int limit = 10; void speak(String message); void eat(String food); }
Example of an Interface
// This class provides the implementation for the UserAction interface class UserService implements UserAction{ @overide void speak(String message){ // logic goes here and can be long System.out.println(message); } @overide void eat(String food){ // logic goes here and can be long System.out.println("I am eating a "+food); } }
public class Main{ public static void main(String[] args) { UserAction userAction = new UserService(); userAction.speak("Hi my name is Folau"); userAction.eat("burger"); } }
Implements Multiple Interfaces
public interface UserAction { int limit = 10; public void speak(String message); public void eat(String food); }
public interface MachineAction { public void run(); }
public class ActionService implements UserAction, MachineAction{ @Override public void run() { System.out.println("run"); } @Override public void speak(String message) { System.out.println(message); } @Override public void eat(String food) { System.out.println("I am eating a "+food); } }
public class Main { public static void main(String[] args) { ActionService actionService = new ActionService(); actionService.eat("burger"); actionService.run(); } }