What will be the output of the code given below?

class Parent{
    public final void displayMessage() {
        System.out.println("displayMessage() method of Parent invoked");
    }
}

class Child extends Parent{
    public void displayMessage() {  
        System.out.println("displayMessage() method of Child invoked");
    }
}

public class Tester{
    public static void main(String[] args) {
        Parent parent = new Child();
        parent.displayMessage();
    }
}

displayMessage() method of Parent invoked

displayMessage() method of Child invoked

Compilation error as final method cannot be overridden

displayMessage() method of Parent invoked displayMessage() method of Child invoked

Verified Answer
Correct Option - c
Anush said

The correct answer is: Compilation error as final method cannot be overridden.
Here's why:
1. The displayMessage() method in the Parent class is marked as final, which means it cannot be overridden by any subclass.
2. In the Child class, the code attempts to override the displayMessage() method from the Parent class, which is not allowed because of the final keyword.
3. As a result, the code will not compile and will result in a compilation error.

To get all Self Assessment - Programming using Java Exam questions Join Telegram Group https://rebrand.ly/lex-telegram-236dee

Telegram