Interface in Java: Definition, Rules, and Examples

Interface in Java

An interface is a type definition block in Java that is completely abstract. It is used to achieve full abstraction and to define a contract that implementing classes must follow.

Key Points

  • An interface is declared using the interface keyword.
  • An interface can contain:
           ✓public static final variables (constants)
          ✓public abstract methods (instance methods)
  • An interface cannot be instantiated (object creation is not allowed).
  • An interface can extend another interface using the extends keyword.
  • A class can implement an interface using the implements keyword.
  • An interface cannot extend a class.
  • An interface supports complete abstraction because it contains only abstract methods.
  • An interface supports multiple inheritance

Example

interface Animal {
    int AGE = 5; // public static final by default

    void sound(); // public abstract by default
}

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

Multiple Inheritance Using Interface

interface A {
    void show();
}

interface B {
    void display();
}

class C implements A, B {
    public void show() {
        System.out.println("Show method");
    }

    public void display() {
        System.out.println("Display method");
    }
}
Contracts Between Interface and Implementing Class

Contract 1

If a class implements an interface, then the class must provide implementations for all abstract methods declared in the interface.
👉 Implementation means method overriding

Contract 2

If a class implements an interface but does not provide implementations for the abstract methods, then the class must be declared abstract.

abstract class Sample implements Animal {
    // No implementation provided
}

Important Notes

  • All methods in an interface are public and abstract by default.
  • All variables in an interface are public, static, and final by default.
  • Interfaces are widely used to achieve loose coupling and multiple inheritance in Java.

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know