1. What is an Interface in Java?
An interface in Java is a blueprint of a class that only contains method signatures (no implementation). It is used to achieve abstraction and multiple inheritance in Java.
💡 Key Points:
- No method implementation – Only method declarations.
- Implemented by classes – Classes provide the actual implementation of the methods.
- Supports multiple inheritance – A class can implement multiple interfaces.
2. Creating a Java Interface
Step 1: Define an Interface
interface WordPress {
void publishPost(String title, String content); // Abstract method
}
🔹 Explanation:
- This interface defines the
publishPost()
method. - Any class that implements this interface must provide an implementation.
Step 2: Implement the Interface
WordPressAPI implements WordPress {
private String apiUrl;
private String username;
private String password;
public WordPressAPI(String apiUrl, String username, String password) {
this.apiUrl = apiUrl;
this.username = username;
this.password = password;
}
@Override
public void publishPost(String title, String content) {
// Simulating an API request (Replace this with real API call)
System.out.println("Connecting to WordPress API at: " + apiUrl);
System.out.println("Authenticating as: " + username);
System.out.println("Publishing Post:");
System.out.println("Title: " + title);
System.out.println("Content: " + content);
System.out.println("Post published successfully!");
}
}
🔹 Explanation:
WordPressAPI
implements theWordPress
interface.- It provides the actual implementation of
publishPost()
.
Step 3: Using the Interface
class Main {
public static void main(String[] args) {
// WordPress API credentials (Replace with real values)
String apiUrl = "https://example.com/wp-json/wp/v2/posts";
String username = "admin";
String password = "password";
// Creating an instance of WordPressAPI
WordPress myBlog = new WordPressAPI(apiUrl, username, password);
// Publishing a blog post
myBlog.publishPost("My First Post", "This is the content of my blog post.");
}
}
3. How It Works
✅ Step 1: The WordPress
interface defines the method but does not implement it.
✅ Step 2: The WordPressAPI
class implements the interface and provides the real functionality.
✅ Step 3: The Main
class uses the WordPressAPI
class via the WordPress
interface.
4. Benefits of Using Interfaces
✅ Loose Coupling
- The
Main
class does not depend on the actual implementation (WordPressAPI
). - If we need a different WordPress API implementation, we can easily replace it.
✅ Multiple Implementations
- We can create another class (
WordPressMockAPI
) to simulate API responses for testing.
✅ Flexibility & Scalability
- New API implementations can be added without modifying existing code.