Challenge - 5 Problems
Method Overriding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of overridden method call
What is the output of the following Java code?
Java
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Attempts:
2 left
π‘ Hint
Remember that the method called depends on the actual object type, not the reference type.
β Incorrect
The variable 'a' is of type Animal but refers to a Dog object. The overridden method in Dog is called, so it prints 'Bark'.
β Predict Output
intermediateOutput with super keyword in overridden method
What will be printed when this Java program runs?
Java
class Parent { void show() { System.out.println("Parent show"); } } class Child extends Parent { @Override void show() { System.out.println("Child show"); super.show(); } } public class Main { public static void main(String[] args) { Child c = new Child(); c.show(); } }
Attempts:
2 left
π‘ Hint
The super keyword calls the parent class method inside the overridden method.
β Incorrect
The Child's show method prints 'Child show' first, then calls super.show() which prints 'Parent show'.
π§ Debug
advancedIdentify the error in method overriding
Which option correctly identifies the error in this code snippet?
Java
class Base { void display() {} } class Derived extends Base { int display() { return 1; } }
Attempts:
2 left
π‘ Hint
Check if the return type matches when overriding a method.
β Incorrect
Overriding methods must have the same return type (or a subtype). Here, void and int differ, causing a compilation error.
π§ Conceptual
advancedEffect of private method on overriding
What happens if a method in the parent class is private and a method with the same signature is declared in the child class?
Attempts:
2 left
π‘ Hint
Private methods are not visible to child classes.
β Incorrect
Private methods are not inherited, so the child method is independent and does not override the parent method.
β Predict Output
expertOutput with method overriding and casting
What is the output of this Java program?
Java
class A { void print() { System.out.println("A"); } } class B extends A { @Override void print() { System.out.println("B"); } } class C extends B { @Override void print() { System.out.println("C"); } } public class Main { public static void main(String[] args) { A obj = new C(); ((B) obj).print(); } }
Attempts:
2 left
π‘ Hint
Casting does not change the actual object type; overridden method of actual object is called.
β Incorrect
The object is of type C. Even when cast to B, the overridden print() in C is called, printing 'C'.
