Subclass Method Overrides Interface Method with Different Behavior In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method from an interface and implements the same method with different behavior

The code defines an interface Printable with a method print, and two classes, Printer and Scanner, both of which implement the Printable interface by providing their respective implementations for the print method. In the Main class, you create instances of both Printer and Scanner, assign them to Printable references, and then call the print method on each of them. Here's an explanation of the code:

  • Printable is an interface with a single 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 prints "Printing..." to the console.
  • Scanner is another class that also implements the Printable interface with its implementation of the print method. The print method in the Scanner class prints "Scanning..." to the console.
  • In the Main class, you create instances of both Printer and Scanner classes and store them in Printable references, demonstrating polymorphism.
  • You then call the print method on both the printer and scanner objects, which invokes the respective print methods in their respective classes.

Source Code

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

Output

Printing...
Scanning...