Skip to content
Sharp

Core Java · interview question

Given the following code, why does it compile and execute successfully? interface Order { void process(); } class OnlineOrder implements Order { public void process() { System.out.println("Online Order Processed"); } } public class Main { public static void main(String[] args) { Order order = new OnlineOrder(); order.process(); } }?

Multiple choiceHardchapter-5-curatedpremiumcore-javaupcasting-and-dynamic-dispatch
java
interface Order { void process(); }
class OnlineOrder implements Order { public void process() { System.out.println("Online Order Processed"); } }
public class Main { public static void main(String[] args) { Order order = new OnlineOrder(); order.process(); } }
Choose one answer
Answer and explanation

Correct answer

B. Interfaces allow upcasting, enabling polymorphic behavior.

Why

Interfaces in Java allow upcasting, which means an OnlineOrder object can be treated as an Order reference. This enables polymorphic behavior, allowing the process method to be called on the interface reference, executing the overridden method in the OnlineOrder class.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →