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
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(); } }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.
More Core Java questions
- What happens if a class implements two interfaces that have methods with the same signature?
- Given the code snippet below, what will be the result of the comparison using '=='?
- Which of the following variable names is best for storing the total amount in a shopping cart?
- When does a local variable declared inside a method stop existing?
- Which of the following is a checked exception?
- Why might you choose 'int' over 'long' for storing the number of items in a small store's inventory?