Interfaces for Custom Document Printing in Java


Create a Java program to demonstrate the use of an interface for custom document printing

  • The DocumentPrinter interface declares two methods: printDocument for printing a document and cancelPrinting for canceling the printing process.
  • In the main method of the Main class, an anonymous class is created that implements the DocumentPrinter interface.
  • Inside the anonymous class, the printDocument method prints the document to the console, and the cancelPrinting method cancels the printing process.
  • A sample document string is created.
  • The printDocument and cancelPrinting methods of the DocumentPrinter interface are called to demonstrate printing and canceling printing.

Source Code

interface DocumentPrinter
{
	void printDocument(String document);
	void cancelPrinting();
}
 
public class Main
{
	public static void main(String[] args)
	{
		DocumentPrinter documentPrinter = new DocumentPrinter()
		{
			@Override
			public void printDocument(String document)
			{
				System.out.println("Printing document : " + document);// Implement document printing logic here
			}
 
			@Override
			public void cancelPrinting()
			{
				System.out.println("Document printing canceled");// Implement cancel printing logic here
			}
		};
 
		String document = "Sample Document";
 
		documentPrinter.printDocument(document);// Print document
 
		documentPrinter.cancelPrinting();// Cancel printing
	}
}

Output

Printing document : Sample Document
Document printing canceled

Example Programs