Search Logic Blocks

Tuesday, March 23, 2021

Java: Nested Class in an Interface

We already discussed about interfaces, partial interface and nested interface in a class. In this post, we will learn, how we can declare a class inside an interface. The outer interface can access the inner class in its own methods. Suppose there is an interface named as Magazine, and it has inner class named as Article. A class MagazineDemo implements the interface Magazine and creates an instance of inner class Article -

// Interface Magazine - prototype of a magazine
public interface Magazine {

// Prints the article
void postArticle(Article a);

// Gets the number of characters in an Article
int getArticleLen(Article a);

// Gets the number of words in an Article
int getArticleWords(Article a);

// Class Article in the interface Magazine
class Article {
String title;
String author;
String content;

// Article class constructor
Article(String title, String author, String content) {
this.title = title;
this.author = author;
this.content = content;
}
}
}
The interface Magazine is implemented by a demo class MagazineDemo. The main() method creates an instance of inner class Article and calls the implemented methods to print the Article details -
import java.util.Scanner;

// Implements the interface Magazine
public class MagazineDemo implements Magazine {
// Prints the Article
public void postArticle(Article a) {
System.out.println("title: " + a.title);
System.out.println("author: " + a.author);
System.out.println("content: " + a.content);
}

// Implements the interface method - getArticleLen(Article a)
public int getArticleLen(Article a) {
int len = a.content.length();
System.out.println("Article has " + len + " characters.");
return len;
}

// Implements the interface method - getArticleWords(Article a)
public int getArticleWords(Article a) {
String words[] = a.content.split(" ");
int wordCount = words.length;
System.out.println("Article has " + wordCount + " words.");
return wordCount;
}

public static void main(String args[]) {
System.out.print("Enter title:");
Scanner sc = new Scanner(System.in);
String title, author, content;
title = sc.nextLine();

System.out.print("Enter author name:");
author = sc.nextLine();

System.out.print("Enter content:");
content = sc.nextLine();
System.out.println("----------------");

MagazineDemo d = new MagazineDemo();
Article a = new Article(title, author, content);
d.getArticleLen(a);
d.getArticleWords(a);
d.postArticle(a);
}
}
Here is the example of output -

Enter title:Implementing Interfaces
Enter author name:Herbert Schildt
Enter content:Once an interface has been defined, one or more classes can implement that interface.
----------------
Article has 85 characters.
Article has 14 words.
title: Implementing Interfaces
author: Herbert Schildt
content: Once an interface has been defined, one or more classes can implement that interface.

The code can be found at Github Link.

No comments: