Interface in Java: An interface in Java is a blueprint of a class that defines a set of abstract methods (methods without a body) and constants. It is used to achieve:
- Loose Coupling: Interfaces decouple code, allowing flexibility in implementation.
- Abstraction: By providing abstract methods, it hides implementation details.
- Multiple Inheritance: Java supports multiple inheritance via interfaces, unlike classes.
What is an Interface in Java?
- An interface cannot contain a method body (except for default and static methods since Java 8).
- Interfaces can contain only public, static, and final constants.
- Interfaces can have method declarations without a body; implementation is done by classes that implement the interface.
- Interfaces represent the IS-A relationship.
- You cannot instantiate an interface directly.
Java interfaces are useful for three main reasons:
Why Use Java Interfaces?
- Abstraction: Interfaces define abstract methods without detailing how they should be implemented.
- Multiple Inheritance: A class can implement multiple interfaces, providing the ability to inherit behaviour from more than one source.
- Loose Coupling: Interfaces separate method definitions from their implementations, allowing more flexibility.
Read also: Abstract Class in Java: A Comprehensive Overview with 5 Examples
How to Declare an Interface?
The syntax for declaring an interface:
interface InterfaceName {
// Declare constant fields (public, static, final by default)
// Declare abstract methods (public and abstract by default)
}
Example:
interface Animal {
void sound(); // abstract method
}
In this example, any class implementing Animal must provide its implementation of sound().
Java Interface Example
Let’s see a simple example of an interface and a class implementing it:
interface Printable {
void print();
}
class Document implements Printable {
public void print() {
System.out.println("Printing document...");
}
public static void main(String[] args) {
Document doc = new Document();
doc.print();
}
}
Output:
Here, Document class implements the Printable interface and provides its own implementation of the print() method.
Multiple Inheritance via Interface
In Java, a class can implement multiple interfaces. This is how Java handles multiple inheritance:
interface Printable {
void print();
}
interface Showable {
void show();
}
class InterfaceDemo implements Printable, Showable {
public void print() {
System.out.println("Hello");
}
public void show() {
System.out.println("Welcome");
}
public static void main(String[] args) {
InterfaceDemo demo = new InterfaceDemo();
demo.print();
demo.show();
}
}
Output:
Hello
Welcome
Interface vs Class (Multiple Inheritance)
Java does not support multiple inheritance with classes due to ambiguity. However, interfaces do not cause this ambiguity, because:
- Interfaces only provide method signatures.
- The implementing class provides the actual behaviour, eliminating any ambiguity.
//Interface vs Class
interface Printable {
void print();
}
interface Showable {
void print();
}
class TestInterface implements Printable, Showable {
public void print() {
System.out.println("Printing without ambiguity");
}
public static void main(String[] args) {
TestInterface obj = new TestInterface();
obj.print();
}
}
Output:
Printing without ambiguity
Java 8 Enhancements in Interfaces
Default Methods
Java 8 introduced default methods in interfaces, allowing methods with a body:
interface Drawable {
void draw();
default void message() {
System.out.println("Default message");
}
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing Circle");
}
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.message();
}
}
Output:
Drawing Circle
Default message
Static Methods
Interfaces in Java 8 can also have static methods, which can be accessed without instantiating the interface:
interface Calculator {
static int square(int x) {
return x * x;
}
}
class TestStaticMethod {
public static void main(String[] args) {
System.out.println(Calculator.square(4)); // Output: 16
}
}
Marker Interface
A Marker Interface is an interface with no methods or fields. It is used to signal to the JVM or compiler that the class implementing it has a special characteristic. Common marker interfaces include:
- Serializable
- Cloneable
Example of a marker interface:
public interface Serializable {
// no methods or fields
}
Nested Interfaces
Java allows interfaces to be nested within other interfaces. This is called a nested interface:
interface OuterInterface {
void outerMethod();
interface InnerInterface {
void innerMethod();
}
}
class TestNestedInterface implements OuterInterface.InnerInterface {
public void innerMethod() {
System.out.println("Nested interface method");
}
public static void main(String[] args) {
TestNestedInterface test = new TestNestedInterface();
test.innerMethod();
}
}
Output:
Nested interface method
Read also: Comprehensive Guide to the iomanip Library in C++
Comparison Between Abstract Class and Interface In Java
Feature | Abstract Class | Interface |
Multiple Inheritance | Cannot support multiple inheritance (a class can only extend one abstract class). | Supports multiple inheritance (a class can implement multiple interfaces). |
Implementation | Can have both abstract methods (without body) and concrete methods (with body). | Can have abstract methods (without body). Since Java 8, can also have default and static methods with body. |
Variables | Can have instance variables (non-final) and constants. | Only allows public, static, and final variables (constants). |
Constructors | Can have constructors. | Cannot have constructors (cannot be instantiated). |
Access Modifiers for Methods | Can have methods with any access modifier (public, protected, private). | All methods are implicitly public (abstract methods). |
Inheritance Type | Use extends keyword for inheritance. | Use implements keyword for implementation by a class. |
Default Method Support | Can have regular methods with a body. | From Java 8 onwards, supports default methods with a body. |
Static Methods | Can have static methods. | Can have static methods (introduced in Java 8). |
Private Methods | Can have private methods. | Can have private methods (introduced in Java 9). |
When to Use | Used to achieve 100% abstraction and when unrelated classes need to share behaviour. | Represents a “CAN-DO” relationship (class to behaviour). |
IS-A Relationship | Represents an “IS-A” relationship (class to subclass). | Can have abstract methods (without body). Java 8, can also have default and static methods with body. |
Inheritance Depth | A class can extend only one abstract class. | A class can implement multiple interfaces. |
Performance | Slightly faster since abstract classes are closer to regular classes. | Slightly slower due to additional indirection for method calls. |
Fields/Attributes | Can contain fields, both static and non-static. | Can only contain static and final fields (constants). |
Type of Methods | Before Java 8, only abstract methods. After Java 8, can have abstract, default, and static methods. | Used when classes share common behaviour but need some methods to be implemented differently by subclasses. |
Summary of Key Points Interface in Java:
- Interface is a blueprint for classes, containing abstract methods.
- Multiple Inheritance is supported via interfaces.
- Java 8 added default and static methods to interfaces.
- Marker Interface indicates a specific behavior to the JVM.
- Nested Interfaces are interfaces within interfaces.