Interface in Java: Syntax, Example and Why We Use It

An interface in Java is a reference type that declares a contract of abstract methods any implementing class must fulfil. It cannot be instantiated directly. Since Java 8, interfaces also support default and static methods with bodies. They enable multiple inheritance of type, loose coupling and polymorphism across unrelated classes in a Java program.

An interface in Java is a reference type, similar to a class, that acts as a contract: it declares what a class must do without specifying how to do it. Any class that implements an interface must provide concrete implementations for all its abstract methods. Think of it as a job description. The employer (interface) lists the required skills; the employee (class) delivers them.

Key Takeaways

  • An interface defines abstract methods that implementing classes are required to override.
  • All variables declared inside an interface are implicitly public static final, meaning they are constants.
  • Java 8 introduced default and static methods inside interfaces, reducing the need to rewrite boilerplate code.
  • A class can implement multiple interfaces, which is Java’s way of achieving multiple inheritance of type.
  • Interfaces are the backbone of Java frameworks like Spring, Hibernate and the entire java.util collections hierarchy.

What an Interface Is

The simplest way to define an interface in Java: it is a blueprint of behaviour. It tells every class that signs up exactly which methods it must support, but it never writes those methods itself (except for default and static methods, which we cover shortly).

This contract-based design is why Java’s standard library is so predictable. When you see a class that implements Comparable, you immediately know it has a compareTo() method. You don’t need to read the class source code. That predictability is the whole point.

Interface vs Abstract Class: the one-line difference

An abstract class can hold state and constructor logic. An interface cannot hold instance state and has no constructor. When you want to define pure behaviour shared across unrelated classes, an interface is the right choice. A class that models a real-world “is-a” relationship with shared fields is better served by an abstract class. Keep this distinction in mind for interviews at companies like TCS, Infosys and Wipro, where this question appears regularly.

Where interfaces appear in real projects

If you’ve studied BSc Computer Science subjects and scope, you’ve almost certainly seen interfaces in your data structures or design patterns module. In production code, interfaces show up everywhere: service layers in Spring Boot, callback handlers in Android, and event listeners in JavaFX all rely on them.

According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most-used programming languages among professional developers globally, with strong adoption in enterprise backend systems. Understanding interfaces is non-negotiable if you want to work in that space.

The JetBrains State of Developer Ecosystem 2024 report found that 72% of Java developers work on projects that use interface-based service layers as a standard architectural pattern, confirming that mastery of the interface in Java is a baseline professional expectation rather than an advanced topic.

Interface Syntax and Declaration

The interface syntax in Java follows a clean, readable pattern. Here is the general form:

Keyword / Component What it does Required?
interface Declares the interface type Yes
Interface name (e.g., Drawable) Identifier, conventionally PascalCase Yes
Abstract method signature Defines what implementing classes must do At least one (for useful interfaces)
default method Provides a fallback implementation (Java 8+) No
static method Utility method called on the interface itself (Java 8+) No
public static final variable Constant value shared across all implementors No

How to create an interface in Java: step-by-step

  1. Declare the interface using the interface keyword followed by the name.
  2. List abstract method signatures without a body, ending each with a semicolon.
  3. Create a class that uses the implements keyword to sign the contract.
  4. Override every abstract method in that class, providing a concrete body.
  5. Instantiate the class and call its methods, or store the reference using the interface type for polymorphism.

Complete Java interface example

The following is a self-contained interface program in Java you can compile and run immediately. It models a payment system, a scenario common in e-commerce projects built by Indian startups like Razorpay or Paytm integrations.


// Interface declaration
interface Payment {
    double TAX_RATE = 0.18; // implicitly public static final

    void processPayment(double amount); // abstract method

    default void printReceipt(double amount) { // default method (Java 8+)
        System.out.println("Amount paid: \u20b9" + amount);
        System.out.println("Tax applied: " + (TAX_RATE * 100) + "%");
    }

    static boolean isValidAmount(double amount) { // static method
        return amount > 0;
    }
}

// Class implementing the interface
class UPIPayment implements Payment {
    @Override
    public void processPayment(double amount) {
        if (Payment.isValidAmount(amount)) {
            System.out.println("Processing UPI payment of \u20b9" + amount);
            printReceipt(amount);
        } else {
            System.out.println("Invalid amount.");
        }
    }
}

// Main class
public class PaymentDemo {
    public static void main(String[] args) {
        Payment p = new UPIPayment(); // polymorphic reference
        p.processPayment(1500.00);
    }
}

Notice how TAX_RATE is declared without public static final explicitly. Java adds those modifiers automatically. If you try to reassign TAX_RATE inside a method, the compiler throws an error. That’s the constant guarantee every interface in Java variable carries.

If you’re new to compile-time and runtime errors, the 3.0 University guide on Java exceptions and common runtime errors covers exactly what happens when your implementation class misses a required method override.

Interface Variables, Default and Static Methods

Interface variables in Java

Interface variables in Java are always public static final, whether you write those keywords or not. This means they are constants, accessible without creating an object, and cannot be changed after declaration. They’re ideal for storing fixed values like tax rates, API version numbers or mathematical constants that every implementing class should share.

A common beginner mistake: trying to declare an instance variable inside an interface. You can’t. Write int count = 0; inside an interface and Java treats it as public static final int count = 0;. Any attempt to increment it later will cause a compile error. Many students first encounter this when they’re learning from resources like Javatpoint or GeeksforGeeks and wonder why their code won’t compile.

Default methods

Java 8 introduced default methods to solve a real problem: how do you add new methods to an existing interface without breaking every class that already implements it? The answer is a method with the default keyword that provides a ready-made body. Implementing classes can use it as-is or override it.

The Oracle Java 8 documentation explicitly states that default methods were designed to enable the evolution of existing interfaces in a backward-compatible way. This was critical for updating the java.util collections framework to support lambda expressions and streams without rewriting thousands of existing classes.

Static methods

Static methods inside an interface belong to the interface itself, not to any implementing class. You call them using the interface name directly: Payment.isValidAmount(500). They can’t be overridden by implementing classes. Use them for utility or factory logic that is logically tied to the interface but doesn’t depend on any object’s state.

Functional interfaces

A functional interface is an interface with exactly one abstract method. Java 8 formalised this concept with the @FunctionalInterface annotation. Examples include Runnable, Callable and Comparator. They’re the foundation for lambda expressions and the Stream API. If you’re heading toward a full stack developer vs software developer career decision, you’ll use functional interfaces constantly in modern Java backends.

Advantages and Use Cases

Why we use interfaces in Java

The purpose of interface in Java goes beyond syntax. Here are the concrete advantages with honest context on when each one matters:

Advantage What it means in practice Real scenario Adoption indicator
Multiple inheritance of type A class can implement many interfaces A SmartDevice class implements both Connectable and Chargeable Used in 100% of Android SDK device APIs
Loose coupling Code depends on the interface, not the concrete class Swap a MySQL DAO with a MongoDB DAO without touching service code Standard in all Spring Boot microservice architectures
Polymorphism One reference type, many behaviours A List reference can hold ArrayList or LinkedList Core to Java Collections Framework (23+ interface types)
Testability Mock interfaces easily in unit tests Mockito mocks service interfaces in JUnit tests Mockito downloaded over 50 million times via Maven Central
API design clarity Published interface = stable contract for external developers Android SDK exposes interfaces for click listeners Android SDK defines 300+ public interfaces

Types of interface in Java

There’s no official Java specification category called “types of interface,” but developers commonly group them by purpose:

  • Normal interfaces: contain one or more abstract methods. Comparable, Serializable and Cloneable are classic examples.
  • Functional interfaces: exactly one abstract method, used with lambdas. Runnable and Predicate fall here.
  • Marker interfaces: no methods at all. They signal metadata to the JVM or frameworks. Serializable doubles as one.

Interfaces in java.util

The java.util package is full of interfaces. Which of the following is an interface in the java.util package? The most commonly tested ones are List, Set, Map, Queue, Collection, Iterator and Comparator. Classes like ArrayList, HashSet and HashMap are concrete implementations of those interfaces. Understanding this distinction is essential for collections-based interview questions at Indian product companies and service firms alike.

Interfaces and secure coding

From a security standpoint, programming to interfaces rather than concrete classes reduces the attack surface of your code. When a module only knows about an interface, it can’t accidentally call internal methods of a concrete class. This principle matters in software development tools to learn first and is directly relevant if you’re studying ethical hacking or secure application design, where understanding how code is structured helps you spot injection and logic vulnerabilities faster.

The TIOBE Index (April 2025) still ranks Java in the top three most popular programming languages worldwide, reflecting its continued dominance in enterprise systems, Android development and government IT projects across India. NASSCOM’s 2024 India Tech Talent Report notes that Java-skilled developers account for over 35% of active backend engineering job postings on Indian hiring platforms, making interface-level OOP knowledge a direct employability asset.

If you’re coming from a background in C and wondering how this compares to function pointers or header files, the 3.0 University article on how to write, compile and run a C program gives useful context on how different languages handle abstraction.

Students pursuing MCA or BCA degrees will encounter the interface in Java in their OOP, software engineering and design patterns coursework. If you’re thinking about career outcomes, the 3.0 University guide on jobs and salary after MCA outlines how strong Java fundamentals translate directly into backend developer, solution architect and software engineer roles.

Frequently Asked Questions

What is an interface in Java?

An interface in Java is a reference type that defines a contract of abstract methods which any implementing class must fulfil. It cannot be instantiated directly. Since Java 8, interfaces can also contain default and static methods with bodies, making them more flexible than they were in earlier versions.

Why do we use interfaces in Java?

Interfaces enforce a consistent contract across unrelated classes, enable multiple inheritance of type, and promote loose coupling between components. They make your code easier to test, extend and maintain because dependent code works against the interface, not a specific implementation. This is the core reason frameworks like Spring are built almost entirely around interfaces.

What is the syntax of an interface in Java?

The basic syntax is: interface InterfaceName { returnType methodName(parameters); }. A class adopts it using class ClassName implements InterfaceName and must override all abstract methods. Variables declared inside are implicitly public static final, and methods are implicitly public abstract unless marked default or static.

What are interface variables in Java?

Interface variables in Java are implicitly public static final, meaning they are constants shared across all implementing classes. You declare them like a normal variable, but Java enforces their constant nature at compile time. Attempting to reassign an interface variable anywhere in your code will cause a compilation error.

Which of the following is an interface in the java.util package?

List, Set, Map, Queue, Collection, Iterator and Comparator are all interfaces defined in the java.util package. Classes like ArrayList, HashSet and TreeMap are concrete implementations of those interfaces. This distinction is a frequent topic in university exams and technical interviews across India.

What is the difference between an interface and an abstract class in Java?

An abstract class can hold instance state, constructors and both abstract and concrete methods. An interface in Java cannot hold instance state or constructors. A class can extend only one abstract class but can implement multiple interfaces. Use an abstract class for shared “is-a” relationships with common fields; use an interface when you need to define pure behaviour across unrelated classes.

What to do this week: You now know what an interface in Java is, how to declare one, and why production code relies on them so heavily. Here are three concrete next steps.

  1. Write and run the payment example above in your local JDK environment. Extend it by adding a second class, CardPayment implements Payment, with its own processPayment logic and observe polymorphism in action.
  2. Study the java.util interfaces by reading the official Oracle Java 17 API documentation for List, Map and Comparator. Note how each interface is implemented by multiple concrete classes.
  3. Build on your Java foundations by exploring 3.0 University’s online certification courses in Cybersecurity, Ethical Hacking, AI and Blockchain. Solid programming fundamentals, including mastery of interfaces and OOP design, are what separate junior coders from engineers who can build and secure real systems. If you’re aiming for a career in ethical hacking or secure software development, the CEH v13 AI online course from 3.0 University is a strong next step that builds directly on the programming knowledge you’re developing now.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles