An interface may consist of constants, default methods, abstract methods (without body )and static methods. It explains what a class should do and look like, but not how. It can be extended by other interfaces using ‘ extends’ and implemented by other classes using ‘implements’ keyword.
It cannot be instantiated, further, the class that implements it must provide the body for the implemented abstract method, otherwise, compiler triggers an error. An interface is followed by ‘interface’ keyword.
If no modifier is mentioned, then the interface would only be accessed within a package.
In an interface, you can define an abstract method, and that method must be overridden by the class that implements it. In other words, A class which implements an interface must define the body of that abstract method.
Program:
interface Quadilateral{ void area(); // abstract method } class rectangle implements Quadilateral{ int length; int breadth; @Override public void area(){ System.out.println("Area of rectangle = "+(length*breadth)+" cm sq."); } } class square{} public class InterfaceExample { public static void main(String[] args) { rectangle obj =new rectangle(); obj.length =10; obj.breadth=5; obj.area(); } }
Output:
void area();
By default, a compiler treats a method within an interface like this:
// abstract returnType methodName(); abstract void area();
Interface also allow us to declare constants whose declaration and initialization takes place at a single statement.
Program:
interface Pie{ // Compiler would see this statement as public static final double =3.14; double pie =3.14; // Constant } class Showing implements Pie{ void print(){ System.out.println(" I am Printing constant value "+pie); } } public class InterfaceConstant { public static void main(String[] args) { Showing obj =new Showing(); obj.print(); } }
Output:
double pie =3.14;
By default, a compiler treats a variable as constant within an interface like this:
//public static final constantName = value; public static final pie= 3.14;
A static method doesn’t depend upon the instance of a class. Therefore, it executes independently.
Program:
interface xyz{ static void print(){ System.out.println("Executing static method"); } } class abc implements xyz{ } public class InterfaceStatic implements xyz{ public static void main(String[] args) { xyz.print(); } }
Output:
This post was last modified on July 4, 2022