Interface in Java Tutorial
Chapter 20 · Java Programming Series
PBA Institute 12 min read Intermediate 2024

Interface in Java

An interface is a contract that classes promise to follow. It defines what a class can do, leaving how to each implementing class. Interfaces enable multiple inheritance of type and form the backbone of frameworks like JDBC, JPA and the Collections API.

Key Features

📜

Pure Contract

Originally only abstract methods + constants.

🆕

Default Methods

Java 8+ allows method bodies for backward compatibility.

📦

Static Methods

Interfaces can host static helper methods.

🧩

Multiple Implements

A class may implement many interfaces.

Functional Interface

Single abstract method → lambda target.

🛡️

Loose Coupling

Program to the interface, not the implementation.

Syntax

  • Declare: interface Name { … }
  • Implement: class C implements Name { … }
  • Multiple: class C implements A, B { … }
  • Default method: default void m() { … }

Interface vs Abstract Class

FeatureInterfaceAbstract ClassNote
Methodsabstract + default + staticAny
Fieldspublic static final onlyAny
Multiple inheritYesNo
ConstructorNoYes
UseContractPartial impl

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Interface in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Basic Interface
interface Animal
{
    void sound();
}

class Dog implements Animal
{
    public void sound() { System.out.println("Bark"); }
}

class Main
{
    public static void main(String args[])
    {
        Animal a = new Dog();
        a.sound();
    }
}
Output Bark

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Multiple Interfaces
interface Flyable    { void fly();    }
interface Swimmable  { void swim();   }

class Duck implements Flyable, Swimmable
{
    public void fly()  { System.out.println("Duck flies"); }
    public void swim() { System.out.println("Duck swims"); }
}

class Main
{
    public static void main(String args[])
    {
        Duck d = new Duck();
        d.fly();
        d.swim();
    }
}
Output Duck flies
Duck swims
Default Method (Java 8+)
interface Vehicle
{
    void run();

    default void start() { System.out.println("Starting..."); }
}

class Bike implements Vehicle
{
    public void run() { System.out.println("Bike running"); }
}

class Main
{
    public static void main(String args[])
    {
        Bike b = new Bike();
        b.start();
        b.run();
    }
}
Output Starting...
Bike running
Static Method in Interface
interface Math
{
    static int square(int n) { return n * n; }
}

class Main
{
    public static void main(String args[])
    {
        System.out.println(Math.square(6));
    }
}
Output 36
Functional Interface + Lambda
interface Greeter
{
    void hello(String name);
}

class Main
{
    public static void main(String args[])
    {
        Greeter g = (name) -> System.out.println("Hi " + name);
        g.hello("Aman");
    }
}
Output Hi Aman

Notes & Tips

  • All interface methods are public by default.
  • All interface fields are public static final by default (constants).
  • An interface can extend multiple interfaces.
  • Default methods enable backward compatibility when adding methods to existing interfaces.
  • An interface with exactly one abstract method is a functional interface — lambda compatible.

Real-World Use Cases

Plug-in Architecture

Apps depend on interfaces, swap implementations freely.

Multiple Inheritance

Implement many interfaces to mix capabilities.

API Contracts

JDBC, JPA, Servlet APIs are interfaces.

Lambdas / Streams

Functional interfaces power Java's stream API.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Create a Shape interface with area() and implement Circle and Square.
  • Q2. Define a Drawable and a Resizable interface, and a class that implements both.
  • Q3. Add a default method to an interface and override it in one class.
  • Q4. Use a functional interface with a lambda to filter numbers.
  • Q5. Show why an interface cannot have a constructor.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Difference between abstract class and interface?
Abstract class can have state and constructors; interface focuses on contracts. From Java 8, interfaces also have default methods but no state.
Q2 Can interface methods be private?
From Java 9 onwards, yes — private helper methods used by default methods.
Q3 Does a class have to implement all interface methods?
Yes, unless the class is itself abstract.
Q4 What is a marker interface?
An interface with no methods (e.g., Serializable) used purely for type marking.
Q5 Can interfaces extend multiple interfaces?
Yes — separate them with commas.

FAQ

FAQ 1 Why use interfaces?
To define contracts, support multiple inheritance and enable loose coupling.
FAQ 2 Can interfaces have fields?
Yes, but all are public static final constants.
FAQ 3 Can interfaces have static methods?
Yes — since Java 8.
FAQ 4 What is a functional interface?
Any interface with exactly one abstract method (SAM). Annotated with @FunctionalInterface.
FAQ 5 Can I instantiate an interface?
Not directly — but you can with an anonymous class or a lambda.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Interface in Java:

  • Forgetting the semicolon ; at the end of statements while using Interface.
  • Mixing up similar method names — read Java docs before using new APIs related to Interface.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Inheritance Encapsulation OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Interface — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
InterfaceInterface conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Inheritance — strengthens your understanding of the previous building block.
NEXT Encapsulation — the natural progression after mastering Interface.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Interfaces define contracts in Java: classes promise to provide certain behaviors. Modern interfaces support default and static methods, plus private helpers from Java 9. Use interfaces to model capabilities and enable multiple inheritance of type — the foundation of clean, testable architectures.

Continue Learning