Core Java · interview question
Given the following code, what will be the output and why?
Multiple choiceHardchapter-5-curatedpremiumcore-javaupcasting-and-dynamic-dispatch
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(); } }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.
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?