What is an Interface in Java?
An interface in Java is a blueprint of a class.
It contains:
method declarations (methods without body)
constants (fixed values)
A class that uses an interface must provide the implementation of all its methods.
Interface is used to tell a class what to do, not how to do it.
Or
An interface contains only rules, and the class follows those rules.
Interfaces are used to:
Achieve abstraction
Achieve multiple inheritance
Provide security by hiding implementation
Make code flexible and reusable
Simple Syntax
interface Demo {
void show();
}
class Test implements Demo {
public void show() {
[Link]("Hello");
}
}
Interface Example Using Calculator
interface Calculator {
void add();
void subtract();
}
class MyCalculation implements Calculator {
int a = 20;
int b = 10;
public void add() {
[Link]("Addition = " + (a + b));
}
public void subtract() {
[Link]("Subtraction = " + (a - b));
}
}
public class Main {
public static void main(String[] args) {
MyCalculation m = new MyCalculation();
[Link]();
[Link]();
}
}
Easy Analogy for Students
Real Life Java
School Rules Interface
Students Following Rules Class implementing interface
One-Line Difference Between Class and
Interface
Class Interface
Contains complete methods Contains only method declarations
Describes implementation Describes rules
Very Important Interview Point
Java does not support:
Multiple inheritance using classes
But supports:
Multiple inheritance using interfaces
interface A {
void show();
}
interface B {
void display();
}
class Test implements A, B {
public void show() {
[Link]("Show Method");
}
public void display() {
[Link]("Display Method");
}
}