Subclass Method Overrides Interface Method In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method from an interface

The code defines an interface Printable with a single method print, and a class Printer that implements the Printable interface by providing an implementation for the print method. Then, in the Main class, you create an instance of the Printer class and assign it to a Printable reference, demonstrating polymorphism. Finally, you call the print method on the Printable reference, which invokes the print method in the Printer class. Here's an explanation of the code:

  • Printable is an interface with a method print.
  • Printer is a class that implements the Printable interface by providing an implementation for the print method. The print method in the Printer class simply prints "Printing..." to the console.
  • In the Main class, you create an instance of the Printer class and store it in a variable of type Printable, demonstrating polymorphism. This is possible because Printer implements the Printable interface.
  • You then call the print method on the Printable reference, which invokes the print method in the Printer class. As a result, "Printing..." is printed to the console.

Source Code

interface Printable
{
    void print();
}
 
class Printer implements Printable
{
    @Override
    public void print()
	{
        System.out.println("Printing...");
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Printable printer = new Printer();
        printer.print();
    }
}

Output

Printing...