Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeJava 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
defaultkeyword 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, andfinal. - 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.");
}
}
// 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
- Implementation Contract: Any non-abstract class that implements an interface must provide concrete implementations for all its declared abstract methods.
- Method Bodies: Only
defaultmethods andstaticmethods can have method bodies inside an interface. - 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.
No comments:
Post a Comment