Java Polymorphism: Child Class Method Overriding

let's see how strong your core java is : write the answer in comments: class Parent {   Parent() {     show();   }   void show() {     System.out.println("Parent show");   } } class Child extends Parent {   int x = 10;   void show() {     System.out.println(x);   }   public static void main(String[] args) {     new Child();   } } Questions 1. Which show() is called? 2. Output? 3. Why is this considered dangerous design?

This question is a good example to understand concepts of constructor and inheritance. For the First question: Child class show() method will be called because child class object is created and it overrides the parent class show() method. For the Second question: The output might be 0 because when child class object is created it will first call parent class constructor which then call the overridden show method and print the value of x i.e. 0(Because JVM will first assign default values to the variables after creating the child class object and calls parent constructor first). For the Third question: This can cause security flaws in the code and can result in Null Pointer Exception. You should never call the overridden methods from the constructor, and if you have to call a method from constructor make the method final first.

When you create a child class object then immediately parent class constructor will called in parent class class constructor show method is present So parent show method will called I guess

1. Child.show() is called, reason : actual object is child 2. Output : 0, reason : int x=10 has not been initialized yet 3. overridden methods called before fully initialized subclass

  • No alternative text description for this image
See more comments

To view or add a comment, sign in

Explore content categories