Interface in Java
Apurba Paul
4thFebruary 2025
Introduction
An Interface in Java is a reference type, similar to a class, that can contain
only constants, method signatures, default methods, static methods, and
nested types. It represents a contract that a class must follow, providing a
way to achieve abstraction and multiple inheritance.
Features of Interfaces
• Interfaces can have only abstract methods (before Java 8). From Java
8 onwards, interfaces can include default and static methods.
• A class can implement multiple interfaces, allowing multiple inheritance
in Java.
• All the methods in an interface are implicitly public and abstract (ex-
cept default and static methods).
• Fields in an interface are implicitly public, static, and final.
• Interfaces cannot have constructors, as they cannot be instantiated.
Syntax
The syntax for declaring an interface is as follows:
1 interface InterfaceName {
2 // Constant fields
3 // Abstract methods
4 // Default methods ( from Java 8)
5 // Static methods ( from Java 8)
1
6 }
Example of an Interface
Below is an example demonstrating the use of an interface in Java:
1 interface Animal {
2 // Abstract method
3 void makeSound () ;
4
5 // Default method
6 default void eat () {
7 System . out . println ( " This animal eats food . " ) ;
8 }
9
10 // Static method
11 static void sleep () {
12 System . out . println ( " Animals need sleep . " ) ;
13 }
14 }
15
16 class Dog implements Animal {
17 // Implementing the abstract method
18 public void makeSound () {
19 System . out . println ( " Dog barks . " ) ;
20 }
21 }
22
23 public class Main {
24 public static void main ( String [] args ) {
25 Dog dog = new Dog () ;
26 dog . makeSound () ; // Output : Dog barks .
27 dog . eat () ; // Output : This animal eats
food .
28
29 // Calling static method
30 Animal . sleep () ; // Output : Animals need sleep .
31 }
32 }
2
Multiple Interfaces Implementation
A class can implement multiple interfaces, enabling multiple inheritance in
Java. For example:
1 interface Vehicle {
2 void start () ;
3 }
4
5 interface Machine {
6 void stop () ;
7 }
8
9 class Car implements Vehicle , Machine {
10 public void start () {
11 System . out . println ( " Car is starting . " ) ;
12 }
13
14 public void stop () {
15 System . out . println ( " Car is stopping . " ) ;
16 }
17 }
18
19 public class Main {
20 public static void main ( String [] args ) {
21 Car car = new Car () ;
22 car . start () ; // Output : Car is starting .
23 car . stop () ; // Output : Car is stopping .
24 }
25 }
Key Points to Remember
• A class that implements an interface must override all its abstract meth-
ods.
• A class can implement multiple interfaces, separated by commas.
• Default methods allow interfaces to provide method implementations,
reducing boilerplate code in implementing classes.
• Static methods in interfaces can be called without creating an instance
of the implementing class.
3
• From Java 9, interfaces can include private methods to share common
code among default methods.
Advantages of Interfaces
• Helps achieve full abstraction.
• Supports multiple inheritance.
• Provides a standard way to define contracts for classes.
Advanced Concepts in Interfaces
1. Interface Inheritance
An interface can extend another interface, similar to class inheritance. This
allows the creation of more specific interfaces based on general ones.
1 interface Animal {
2 void makeSound () ;
3 }
4
5 interface Pet extends Animal {
6 void play () ;
7 }
8
9 class Dog implements Pet {
10 public void makeSound () {
11 System . out . println ( " Dog barks . " ) ;
12 }
13
14 public void play () {
15 System . out . println ( " Dog is playing . " ) ;
16 }
17 }
18
19 public class Main {
20 public static void main ( String [] args ) {
21 Dog dog = new Dog () ;
22 dog . makeSound () ; // Output : Dog barks .
23 dog . play () ; // Output : Dog is playing .
24 }
4
25 }
2. Marker Interfaces
A Marker Interface is an interface with no methods or fields. It is used as
a tagging mechanism to convey metadata about a class.
Example: The [Link] interface is a marker interface
that indicates a class can be serialized.
1 import java . io . Serializable ;
2
3 class Employee implements Serializable {
4 private String name ;
5 private int id ;
6
7 public Employee ( String name , int id ) {
8 this . name = name ;
9 this . id = id ;
10 }
11 }
3. Functional Interfaces
A Functional Interface is an interface that contains exactly one abstract
method. These are used for lambda expressions and method references. The
@FunctionalInterface annotation can be used to enforce this rule.
1 @Fun c t i o n a l I n t e r f a c e
2 interface Greeting {
3 void sayHello ( String name ) ;
4 }
5
6 public class Main {
7 public static void main ( String [] args ) {
8 // Lambda expression implementing the functional
interface
9 Greeting greeting = ( name ) -> System . out . println
( " Hello , " + name + " ! " ) ;
10 greeting . sayHello ( " Alice " ) ; // Output : Hello ,
Alice !
11 }
12 }
5
4. Private Methods in Interfaces (Java 9+)
From Java 9 onwards, interfaces can have private methods to share common
code among default methods.
1 interface Calculator {
2 default int add ( int a , int b ) {
3 return calculate (a , b , ’+ ’) ;
4 }
5
6 default int subtract ( int a , int b ) {
7 return calculate (a , b , ’ - ’) ;
8 }
9
10 private int calculate ( int a , int b , char operator ) {
11 return operator == ’+ ’ ? a + b : a - b ;
12 }
13 }
14
15 class MyCalculator implements Calculator {}
16
17 public class Main {
18 public static void main ( String [] args ) {
19 MyCalculator calc = new MyCalculator () ;
20 System . out . println ( calc . add (10 , 5) ) ; //
Output : 15
21 System . out . println ( calc . subtract (10 , 5) ) ; //
Output : 5
22 }
23 }
5. Static Methods in Interfaces
Interfaces can include static methods that can be invoked directly without
an instance.
1 interface MathUtils {
2 static int square ( int number ) {
3 return number * number ;
4 }
5
6 static int cube ( int number ) {
7 return number * number * number ;
8 }
6
9 }
10
11 public class Main {
12 public static void main ( String [] args ) {
13 System . out . println ( MathUtils . square (4) ) ; //
Output : 16
14 System . out . println ( MathUtils . cube (3) ) ; //
Output : 27
15 }
16 }
6. Multiple Interface Implementation with Conflicting
Methods
When a class implements multiple interfaces with conflicting methods, the
class must override the method to resolve the conflict.
1 interface A {
2 default void display () {
3 System . out . println ( " Interface A " ) ;
4 }
5 }
6
7 interface B {
8 default void display () {
9 System . out . println ( " Interface B " ) ;
10 }
11 }
12
13 class C implements A , B {
14 public void display () {
15 System . out . println ( " Resolving conflict in C " ) ;
16 }
17 }
18
19 public class Main {
20 public static void main ( String [] args ) {
21 C obj = new C () ;
22 obj . display () ; // Output : Resolving conflict in
C
23 }
24 }
7
7. Real-World Use Case: Interface for Payment Pro-
cessing
Below is a real-world example where an interface is used to define a contract
for different payment methods.
1 interface Payment {
2 void pay ( double amount ) ;
3 }
4
5 class Credit CardPa yment implements Payment {
6 public void pay ( double amount ) {
7 System . out . println ( " Paid " + amount + " using
Credit Card . " ) ;
8 }
9 }
10
11 class PayPalPayment implements Payment {
12 public void pay ( double amount ) {
13 System . out . println ( " Paid " + amount + " using
PayPal . " ) ;
14 }
15 }
16
17 public class Main {
18 public static void main ( String [] args ) {
19 Payment creditCard = new C reditC ardPay ment () ;
20 creditCard . pay (100.50) ; // Output : Paid 100.5
using Credit Card .
21
22 Payment payPal = new PayPalPayment () ;
23 payPal . pay (200.75) ; // Output : Paid 200.75 using
PayPal .
24 }
25 }
8
8. Interface vs Abstract Class
Feature Interface
Methods All methods are abstract
(except default/static
methods).
Multiple Inheritance A class can implement mul-
tiple interfaces.
Constructors Cannot have constructors.
Fields Fields are public, static,
and final by default.
9. Use of Interfaces in Design Patterns
Interfaces play a crucial role in many design patterns. Below are a few
examples:
9.1 Strategy Pattern
The Strategy Pattern defines a family of algorithms, encapsulates each
one, and makes them interchangeable. Interfaces provide the contract for
different strategies.
1 interface PaymentStrategy {
2 void pay ( double amount ) ;
3 }
4
5 class Cr ed it Ca rd St ra te gy implements PaymentStrategy {
6 public void pay ( double amount ) {
7 System . out . println ( " Paid " + amount + " with
Credit Card . " ) ;
8 }
9 }
10
11 class PayPalStrategy implements PaymentStrategy {
12 public void pay ( double amount ) {
13 System . out . println ( " Paid " + amount + " with
PayPal . " ) ;
14 }
15 }
16
17 class ShoppingCart {
18 private PaymentStrategy paymentStrategy ;
19
9
20 public void s et Pa ym en tS tr at eg y ( PaymentStrategy
paymentStrategy ) {
21 this . paymentStrategy = paymentStrategy ;
22 }
23
24 public void checkout ( double amount ) {
25 paymentStrategy . pay ( amount ) ;
26 }
27 }
28
29 public class Main {
30 public static void main ( String [] args ) {
31 ShoppingCart cart = new ShoppingCart () ;
32
33 cart . set Pa ym en tS tr at eg y ( new Cr edi tC ar dS tr at eg y ()
);
34 cart . checkout (150.0) ; // Output : Paid 150.0 with
Credit Card .
35
36 cart . set Pa ym en tS tr at eg y ( new PayPalStrategy () ) ;
37 cart . checkout (75.5) ; // Output : Paid 75.5 with
PayPal .
38 }
39 }
9.2 Observer Pattern
The Observer Pattern defines a one-to-many dependency between objects
so that when one object changes state, all its dependents are notified. Inter-
faces are used to define the contract for observers.
1 interface Observer {
2 void update ( String message ) ;
3 }
4
5 interface Subject {
6 void attach ( Observer o ) ;
7 void detach ( Observer o ) ;
8 void notifyObservers () ;
9 }
10
11 class NewsAgency implements Subject {
10
12 private List < Observer > observers = new ArrayList < >()
;
13 private String news ;
14
15 public void setNews ( String news ) {
16 this . news = news ;
17 notifyObservers () ;
18 }
19
20 public void attach ( Observer o ) {
21 observers . add ( o ) ;
22 }
23
24 public void detach ( Observer o ) {
25 observers . remove ( o ) ;
26 }
27
28 public void notifyObservers () {
29 for ( Observer observer : observers ) {
30 observer . update ( news ) ;
31 }
32 }
33 }
34
35 class Subscriber implements Observer {
36 private String name ;
37
38 public Subscriber ( String name ) {
39 this . name = name ;
40 }
41
42 public void update ( String message ) {
43 System . out . println ( name + " received update : " +
message ) ;
44 }
45 }
46
47 public class Main {
48 public static void main ( String [] args ) {
49 NewsAgency agency = new NewsAgency () ;
50 Subscriber sub1 = new Subscriber ( " Alice " ) ;
51 Subscriber sub2 = new Subscriber ( " Bob " ) ;
52
11
53 agency . attach ( sub1 ) ;
54 agency . attach ( sub2 ) ;
55
56 agency . setNews ( " Breaking News ! " ) ;
57 // Output :
58 // Alice received update : Breaking News !
59 // Bob received update : Breaking News !
60 }
61 }
10. Interface Segregation Principle
The Interface Segregation Principle (ISP) states that a class should not
be forced to implement interfaces it does not use. This principle is part of
SOLID design principles.
1 interface Printer {
2 void print () ;
3 }
4
5 interface Scanner {
6 void scan () ;
7 }
8
9 class M u l t i F u n c t i o n P r i n t e r implements Printer , Scanner {
10 public void print () {
11 System . out . println ( " Printing ... " ) ;
12 }
13
14 public void scan () {
15 System . out . println ( " Scanning ... " ) ;
16 }
17 }
18
19 class SimplePrinter implements Printer {
20 public void print () {
21 System . out . println ( " Printing ... " ) ;
22 }
23 }
In this example, instead of creating a single interface that combines both
print() and scan() methods, separate interfaces are created to follow ISP.
12
11. Differences Between Interfaces and Abstract Classes
Although interfaces and abstract classes both allow abstraction, they are
fundamentally different. Below is a detailed comparison:
Feature Interface Abstract Class
Nature Provides a contract that Serves as a blueprint for de-
classes must follow. rived classes.
Methods All methods are abstract by Can have both abstract and
default (prior to Java 8). concrete methods.
Can have default and static
methods (from Java 8).
Fields All fields are public Can have instance variables.
static final by default.
Inheritance A class can implement mul- A class can inherit only one
tiple interfaces. abstract class.
Constructors Cannot have constructors. Can have constructors to
initialize state.
12. Interface as a Parameter
Interfaces are often used as method parameters to enhance flexibility and
reusability.
1 interface Drawable {
2 void draw () ;
3 }
4
5 class Circle implements Drawable {
6 public void draw () {
7 System . out . println ( " Drawing a Circle . " ) ;
8 }
9 }
10
11 class Rectangle implements Drawable {
12 public void draw () {
13 System . out . println ( " Drawing a Rectangle . " ) ;
14 }
15 }
16
17 public class Main {
18 public static void printShape ( Drawable shape ) {
19 shape . draw () ;
20 }
13
21
22 public static void main ( String [] args ) {
23 printShape ( new Circle () ) ; // Output : Drawing
a Circle .
24 printShape ( new Rectangle () ) ; // Output : Drawing
a Rectangle .
25 }
26 }
13. Real-World Example: Interface for Logging
Using interfaces in logging systems helps decouple the logging logic from the
application.
1 interface Logger {
2 void log ( String message ) ;
3 }
4
5 class ConsoleLogger implements Logger {
6 public void log ( String message ) {
7 System . out . println ( " Console Log : " + message ) ;
8 }
9 }
10
11 class FileLogger implements Logger {
12 public void log ( String message ) {
13 System . out . println ( " Writing to file : " + message
);
14 }
15 }
16
17 public class Main {
18 public static void main ( String [] args ) {
19 Logger consoleLogger = new ConsoleLogger () ;
20 consoleLogger . log ( " This is a console log . " ) ; //
Output : Console Log : This is a console log .
21
22 Logger fileLogger = new FileLogger () ;
23 fileLogger . log ( " This is a file log . " ) ; //
Output : Writing to file : This is a file log .
24 }
25 }
14
14. Future of Interfaces in Java
• With the addition of default, static, and private methods, interfaces
are becoming more flexible and robust in Java.
• They are expected to play a larger role in functional programming and
API design.
• Enhanced support for interfaces in frameworks like Spring and Hiber-
nate demonstrates their importance in modern Java development.
Conclusion
Interfaces are a cornerstone of Java programming, enabling abstraction, flex-
ibility, and adherence to design principles. By using interfaces effectively,
developers can build robust, scalable, and maintainable applications.
15