Thursday, 27 August 2015

Java Tutorial : What is an Interface (Switch)

Master Core Java Step-by-Step!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!

Subscribe Now on YouTube

Understanding Java Interfaces Through a Real-Life Analogy

In Java, an interface is a blueprint of a class that specifies what a class should do, without dictating how it should do it. While technical definitions can feel abstract, a real-life analogy makes the concept crystal clear.

Think of an electrical switch board on a wall. A switch provides a standard contract: you can turn it ON or turn it OFF. It doesn't matter whether the switch is connected to a bulb, a fan, an air conditioner, or a light—the switch interface remains identical, while each device implements the actual behavior differently.

What Makes an Interface Special?

An interface acts as a contract between the caller and the implementer:

  • 100% Abstraction: Traditional interfaces define method signatures without bodies. They outline what needs to happen, leaving the implementation details entirely to the concrete classes.
  • Loose Coupling: Your application logic depends on the interface contract rather than the concrete implementation details.
  • Multiple Inheritance: Java classes do not support multiple inheritance with classes, but a class can implement multiple interfaces seamlessly.

Code Example: The Switch Analogy in Java

// The Interface (Contract)
interface Switch {
  void switchOn();
  void switchOff();
}

// Implementation 1: Light
class Light implements Switch {
  public void switchOn() {
    System.out.println("Light turned ON: Room is bright!");
  }
  public void switchOff() {
    System.out.println("Light turned OFF: Room is dark!");
  }
}

// Implementation 2: Fan
class Fan implements Switch {
  public void switchOn() {
    System.out.println("Fan turned ON: Air circulating!");
  }
  public void switchOff() {
    System.out.println("Fan turned OFF: Fan stopped!");
  }
}

Both Light and Fan follow the same Switch contract, but each device performs its own unique action when turned on or off.

Key Rules for Java Interfaces

  1. All methods in an interface are implicitly public and abstract (unless defined as default or static).
  2. All variables declared in an interface are implicitly public, static, and final.
  3. A class implements an interface using the implements keyword and must provide concrete implementations for all abstract methods.

Watch More Java Interface Tutorials:

No comments:

Post a Comment

Tutorials