An interface in Java is a blueprint for a class that defines a set of behaviors (methods ) that a class must implement . Interface in java is mainly used to achieve abstraction and multiple inheritance .
Key Characteristics of Java Interface :
- Abstraction : Interface hide the implementation details showing only the basic functionality to the end users.
- Multiple Inheritance : Java classes doesn’t support multiple inheritance . But mutiple inheritance can be achieved using java interfaces. Java class can implement multiple interfaces which allows to inherit behaviors from multiple sources .
- Loose Coupling : Java code that interacts with an object through an interface is not dependent on the specific implementation , but only dependent on the contract which make the code more flexible and easier to maintain.
- Interface cannot be instantiated : Java interface cannot be instantiated i.e. one cannot create an object directly from an interface , a class must implement the interface.
- No Constructors : Interface cannot contain constructors because interface can’t be used to create object.
- Polymorphism : Java interface references can point to objects of any class that implements the interface , allowing for flexible and reusable code that works with different classes.
Example :
//Interface declared
interface Gift {
public static final int t=15;
public abstract void display () ;
}
//Class implementing interface
class Winner implements Gift {
//implementing the abstract method of interface in this class Winner
public void display () {
System.out.println(“Winners are getting incredible gifts “);
}
}
class Demointerface {
public static void main (String args [] ) {
Winner win= new Winner () ;
win.display () ;
System.out.println(“Total winners :”+win.t);
}
}
OUTPUT :
Winners are getting incredible gifts.
Total winners: 15
Relationship Between Class and Interface :
A class can extend another class and similarly , an interface can extend another interface . But only a class can implement an interface and the interface cannot implement class. One interface can extend another interface.
When to Use Class and Interface ?
Use a Class When :
- In Java , use a class when you need to create objects that hold state and perform actions .
- In Java , use a class when you need to represent a real- world entity with attributes and behaviors .
- Classes are used for defining templates for objects with specific functionality and properties .
Use an Interface when :
- Interface is ideal for achieving abstraction and multiple inheritance .
- Use an interface when you need to define a contract for behavior that multiple classes can implement .
To use interface ,use the keyword implements.
