📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Examine the following Java-like code:     

    ```java     class Parent {         String name = "Parent";         public void display() {             System.out.println(name);         }     }     class Child extends Parent {         String name = "Child";         // No display method override     }     public class Main {         public static void main(String[] args) {             Parent p = new Child();             p.display();         }     }     ```     What will be the output?
    A Parent Correct Answer Incorrect Answer
    B Child Correct Answer Incorrect Answer
    C Compilation Error Correct Answer Incorrect Answer
    D Runtime Error Correct Answer Incorrect Answer

    Solution

    This demonstrates variable hiding (not overriding) and method overriding.            `Parent p = new Child();` creates a `Child` object but the reference `p` is of type `Parent`.            When `p.display()` is called, Java uses dynamic method dispatch (polymorphism) to call the `display()` method of the actual object type, which is `Child`.            However, `Child` does not override the `display()` method. Therefore, the `display()` method from the `Parent` class is executed.            Inside `Parent.display()`, `name` refers to `Parent.name`, which is "Parent". The `Child`'s `name` variable is a separate, hidden variable.

    Practice Next
    ask-question