Krivalar Tutorials 
Krivalar Tutorials

Java Interfaces


<Class

Package >







An interface is a type definition which has only method declarations and fields. From Java 8, Interfaces could also have default methods

  • An interface can have default method definitions
  • An interface can have static method definitions
  • An interface can not have non-default and non-static method definitions
  • All methods declared in a interface are implicitly abstract except for default and static methods
  • All variables in an interface are implictly public, static and final
  • All variables in an interface will have values

Java Interface - Example


interface Shape {
float Pi=3.14f;
float calculateArea();
}

interface Vehicle{
void turnSteeringWheel();
void applyBrake();
void accelerate();
void rightIndicator();
void leftIndicator();
void pressHorn();
void trunHeadlights();
void onWiper();
}

Java Interface - static and default methods

  • static methods can be invoked directly by using class name and does not require to be invoked on objects.
  • default methods are used to add method defintions to existing interfaces already implemented by classes.
  • default methods become automatically available to all the implemented classes without any changes.
  • default methods helps to ensure compatibility with existing classes while adding new methods to interfaces
  • default methods helps to add methods taking lambda expressions as parameters

interface Shape {
static void sayHi(){
	System.out.println("Hi");
}
default void sayWelcome(){
	System.out.println("Welcome");
}
}

Java Interface & Class

  • Each Interface can be extended by using the extends keyword.
  • Each Interface can be implemented by using the implements keyword.

<Class

Package >





















Searching using Binary Search Tree