Skip to content
Sharp

Core Java · interview question

Given the following code, what will be the output and why?

Multiple choiceHardchapter-5-curatedpremiumcore-javaupcasting-and-dynamic-dispatch
java
class Book { void print() { System.out.println("Code"); } }
class JavaBook extends Book { void print() { System.out.println("Java"); super.print(); } }
public class Main { public static void main(String[] args) { Book b = new JavaBook(); b.print(); } }
Choose one answer
Answer and explanation

Correct answer

A. Code Java

Why

The method print() in JavaBook overrides the method in Book. When print() is called on a Book reference holding a JavaBook instance, the overridden method in JavaBook is executed. However, for super.print(), the superclass method is called.

Test yourself on Core Java

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

Start free test
All Core Java questions →