Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java interface Keyword
Usage and Examples



interface Keyword in Java

In Java, the interface keyword is used to declare an interface. An interface is a blueprint of a class that contains only abstract methods (until Java 7) and static/final variables. Interfaces help achieve abstraction and support multiple inheritance in Java, which is otherwise not possible with classes.

Why Use Interfaces?

Interfaces are useful when:

Basic Syntax of an Interface

interface InterfaceName {
    // constant variables
    // abstract methods
}

Example: Defining and Implementing an Interface

interface Animal {
    void makeSound();  // abstract method
}

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

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a1 = new Dog();
        Animal a2 = new Cat();

        a1.makeSound();
        a2.makeSound();
    }
}
Bark!
Meow!

Key Rules of Interfaces

Interfaces vs Abstract Classes

AspectInterfaceAbstract Class
Multiple InheritanceSupportedNot supported
ConstructorsNot allowedAllowed
Access ModifiersOnly public methodsAny access modifier
Default BehaviorNo state or constructorsCan have fields and state

Default and Static Methods in Interfaces (Java 8+)

Since Java 8, interfaces can have:

interface Calculator {
    default void greet() {
        System.out.println("Welcome to Calculator!");
    }

    static void info() {
        System.out.println("Calculator Interface v1.0");
    }

    int add(int a, int b);
}

class BasicCalculator implements Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new BasicCalculator();
        c.greet();
        System.out.println("Sum: " + c.add(5, 3));
        Calculator.info();
    }
}
Welcome to Calculator!
Sum: 8
Calculator Interface v1.0

Functional Interfaces (Java 8+)

A functional interface is an interface with exactly one abstract method. These are the basis for lambda expressions.

@FunctionalInterface
interface Printer {
    void print(String msg);
}

public class Main {
    public static void main(String[] args) {
        Printer p = (msg) -> System.out.println(msg);
        p.print("Lambda says hi!");
    }
}
Lambda says hi!

When to Use Interfaces in Real-World Java Apps



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M