← Back to Chapters

Java Interface

? Java Interface

? Quick Overview

An interface in Java is a blueprint of a class that defines a set of abstract methods. It supports multiple inheritance and helps achieve 100% abstraction.

? Key Concepts

  • Interfaces contain abstract methods by default
  • A class uses implements to inherit an interface
  • Interfaces support multiple inheritance
  • Methods are public and abstract by default

? Syntax / Theory

An interface defines what a class must do, not how it does it. A class implementing an interface must provide implementations for all methods.

? View Code Example
// Interface declaration
interface Animal {
void sound();
}

? Code Example(s)

? View Code Example
// Class implementing interface
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}

? Live Output / Explanation

When the sound() method is called using a Dog object, the output will be:

? View Output
// Program output
Dog barks

? Interactive Simulator: Polymorphism

See how the interface Animal acts as a contract. Click buttons to switch implementation!

// Java Code Execution
Animal myPet = new Dog();
myPet.sound();
 
// Output Console
> Dog barks

? Tips & Best Practices

  • Use interfaces to define contracts
  • Prefer interfaces over abstract classes
  • Keep interfaces focused and minimal
  • Use default methods carefully

? Try It Yourself

  • Create an interface Vehicle with method move()
  • Implement it using Car and Bike classes
  • Call methods using interface reference