Bird
0
0

Identify the error in this code:

medium📝 Debug Q7 of 15
Java - Inheritance

Identify the error in this code:

class Parent {
    void show() {
        System.out.println("Parent show");
    }
}
class Child extends Parent {
    void show() {
        System.out.println("Child show");
    }
    void show(int x) {
        System.out.println("Child show with " + x);
    }
}
public class Test {
    public static void main(String[] args) {
        Parent p = new Child();
        p.show(5);
    }
}
APrints 'Child show'
BRuntime error: ambiguous method call
CPrints 'Child show with 5'
DCompilation error: method show(int) not found in Parent
Step-by-Step Solution
Solution:
  1. Step 1: Analyze reference type and method call

    Reference is Parent type, which has only show() without parameters.
  2. Step 2: Check method resolution at compile time

    Compiler looks for show(int) in Parent, not found, so compilation error occurs.
  3. Final Answer:

    Compilation error: method show(int) not found in Parent -> Option D
  4. Quick Check:

    Method call checked by reference type = error if method missing [OK]
Quick Trick: Method calls checked by reference type, not object type [OK]
Common Mistakes:
  • Expecting runtime error instead of compile error
  • Thinking Child's method is called regardless
  • Confusing compile-time and runtime method resolution

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes