Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
Java - Inheritance

What will be the output of the following code?

final class Fruit {
    void taste() { System.out.println("Sweet"); }
}

class Apple extends Fruit {
    void taste() { System.out.println("Sour"); }
}

public class Test {
    public static void main(String[] args) {
        Apple a = new Apple();
        a.taste();
    }
}
ASweet
BSour
CRuntime error
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand final class behavior

    A class declared as final cannot be subclassed.
  2. Step 2: Analyze the code

    Class Apple tries to extend final class Fruit, which causes a compilation error.
  3. Final Answer:

    Compilation error -> Option D
  4. Quick Check:

    Extending final class causes compile-time error [OK]
Quick Trick: Cannot extend a final class [OK]
Common Mistakes:
  • Assuming overriding is allowed on final classes
  • Expecting runtime error instead of compile error
  • Ignoring final keyword effect on inheritance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes