Friday, 29 January 2016

Java Tutorial : Java summary of Interfaces

Master Core Java Concepts!

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

Subscribe Now on YouTube

Java Interfaces: Complete Summary and Recap

In Java, an interface acts as a blueprint of a class or a formal contract between different parts of your application. It specifies what a class must do, while leaving the implementation details to the implementing class itself.

Here is a complete recap summarizing what interfaces can contain, how classes implement them, and how they provide clean abstraction in object-oriented programming.

What Can an Interface Declaration Contain?

An interface declaration can hold several key components:

  • Method Signatures (Abstract Methods): Declares method names, parameter lists, and return types without bodies.
  • Default Methods: Methods defined with the default keyword that carry concrete method bodies for backward compatibility.
  • Static Methods: Utility methods defined directly inside the interface that have concrete bodies and belong to the interface itself.
  • Constant Definitions: Fields declared in an interface, which are implicitly public, static, and final.
  • Nested Types: Nested classes or nested interfaces declared directly within the interface body.

Code Example: Java Interface Overview

public interface Vehicle {
  // Constant definition (implicitly public static final)
  int MAX_SPEED = 120;

  // Abstract method signature
  void start();

  // Default method with implementation
  default void honk() {
    System.out.println("Vehicle is honking!");
  }

  // Static method with implementation
  static void serviceAlert() {
    System.out.println("Service check required.");
  }
}

Core Rules to Remember

  1. Implementation Contract: Any non-abstract class that implements an interface must provide concrete implementations for all its declared abstract methods.
  2. Method Bodies: Only default methods and static methods can have method bodies inside an interface.
  3. Type Reference: An interface name can be used anywhere any other data type name can be used—such as variable declarations, parameter types, or return types.

Watch More Java Interface Tutorials:

No comments:

Post a Comment

Tutorials