Interfaces define a contract of methods that different classes can implement. This allows unrelated classes to be treated the same way, enabling polymorphism and flexible code design.
interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Bark"); } } class Cat implements Animal { public void sound() { System.out.println("Meow"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); a = new Cat(); a.sound(); } }
The interface variable a first refers to a Dog object, so sound() prints "Bark". Then it refers to a Cat object, so sound() prints "Meow".
interface Vehicle { void start(); void stop(); } class Car implements Vehicle { public void start() { System.out.println("Car started"); } // Missing stop() method implementation } public class Test { public static void main(String[] args) { Vehicle v = new Car(); v.start(); v.stop(); } }
In Java, a class that implements an interface must provide concrete implementations for all its methods. Car misses the stop() method, causing a compilation error.
In option A, the method area() has an empty body {} which is not allowed in interfaces unless marked as default or static.
interface Printable { void print(); } interface Showable { void show(); } class Document implements Printable, Showable { public void print() { System.out.println("Printing document"); } public void show() { System.out.println("Showing document"); } } public class Test { public static void main(String[] args) { Document doc = new Document(); doc.print(); doc.show(); } }
Java allows multiple inheritance of type through interfaces. Document implements both Printable and Showable and provides both methods, so both print statements run in order.