Test Your Java Tricky Questions

Test Your Java Tricky Questions

Test Your Java Tricky Questions

Question 1 on Test Your Java Tricky Questions:
What is the output of the following code?

Output:

In child display method
In child display method

(Your guess may be: In parent display method and In child display method). Reason:

Child class is not explicitly calling a superclass constructor, so Java will call the no-argument constructor for you. Looking at the Parent class it’s no-argument constructor invokes the display() method, but this method is also overridden in the Child class so the display() method in the Child class is chosen and displayed by the Parent class. Now the constructor in your Child class is doing the exact same thing and it will also call the display() method, so this explains why your output is:

In child display method // called by the no-argument constructor in the Parent class
In child display method // called by the constructor of the Child class

Pass your comments on this tutorial "Test Your Java Tricky Questions"

One thought on “Test Your Java Tricky Questions

  1. supraja

    its giving the same result if child class constructor called the super class constructor explicitly.please help me out sir.i wrote program as follows.

    class Parent{
    public Parent()
    {
    this.display();
    }
    public void display()
    {
    System.out.println(“in the parent display method”);
    }
    }
    public class Child extends Parent
    {
    public Child()
    {
    super();
    this.display();
    }
    public void display()
    {
    System.out.println(“in the child class display method”);
    }
    public static void main(String[] ar)
    {
    new Child();
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *