Wednesday, 13 January 2016

Java Tutorial : Defining an Interface

Loved This Java Tutorial? Support Ram N Java!

Subscribe to the channel for practical, beginner-friendly core Java and coding tutorials.

SUBSCRIBE ON YOUTUBE

What Is an Interface in Java?

An interface in Java is a blueprint of a class. It provides a formal contract that specifies what a class must do, without mandating how it should do it.

When a class implements an interface, it signs a contract promising to provide concrete implementations for the declared methods. Interfaces are foundational in Java for achieving abstraction and supporting multiple inheritance.

Basic Syntax for Defining an Interface

You declare an interface using the interface keyword followed by the interface name and curly braces containing its members:

public interface Person {
  // Constant fields, abstract methods, default/static methods
}
  • public modifier: Allows the interface to be accessed by any class across any package. If omitted, package-private access applies (accessible only within the same package).
  • interface keyword: Tells the Java compiler that this file is an interface rather than a class.
  • Interface body: Enclosed in curly braces { ... } where methods and constants live.

What Can Go Inside an Interface?

Modern Java allows several types of members inside an interface:

  1. Constants (Variables): All variables declared in an interface are implicitly public static final. You don't need to write those keywords manually.
  2. Abstract Methods: Methods that declare a method signature without a body. Any implementing class must provide the body.
  3. Default Methods: Introduced in Java 8 using the default keyword. They include an implementation and don't break existing classes implementing the interface.
  4. Static Methods: Utility methods with concrete bodies that belong to the interface itself, called via InterfaceName.methodName().
  5. Nested Classes & Interfaces: You can also define nested types inside an interface.

Extending Multiple Interfaces (Multiple Inheritance)

While a Java class can extend only one superclass, an interface can extend multiple interfaces simultaneously using a comma-separated list:

public interface Person extends InterfaceOne, InterfaceTwo, InterfaceThree {
  void introduce();
}

In this scenario, Person becomes the sub-interface, inheriting all abstract definitions from its super-interfaces.

Key Rules to Remember

  • Interfaces cannot be instantiated directly with new.
  • All abstract, default, and static methods are implicitly public.
  • Use interfaces when you want to define a common role across completely unrelated classes.

No comments:

Post a Comment

Tutorials