Java quiz 40: Method overriding

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   By title 
>

This is an advanced quiz to test your skill on method overriding.

Java quiz 40: Method overriding

Level: Hard

What is the output of the following code?

public class MySuper
{
  int x = 1;
  
  public MySuper()
  {
    System.out.print(getResult(3));
  }
  int getResult()
  {
    return x;
  }
  int getResult(int i)
  {
    return(i + x + getResult() + x);
  }
}

public class MySub extends MySuper
{
  int getResult()
  {
    super.x = 5;
    return x + 3;
  }
  public static void main(String[] args)
  {
    new MySub();
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “19” to the standard output.
b. This program writes “13” to the standard output.
c. This program writes “6” to the standard output.
d. This program writes “17” to the standard output.
e. This program writes “16” to the standard output.

Answer explanation

  1. By creating the object of the type MySub, the constructor of the superclass MySuper is called.
  2. The statement System.out.print(getResult(3)); in the constructor is executed and the one-parameter method getResult is invoked.
  3. The method getResult(3) returns (i + x + getResult() + x);
    the parameter i is equal to 3.
    x is equal to 1. remember that after invoking the method getResult() which is overridden in MySub. The statement
    super.x = 5; reassigns the value 5 to the variable x.
    So, the overridden getResult() returns x + 3 = 8.
    The result is i + x + getResult() + x;
    And that is equal to 3 + 1 + 8 + 5 = 17

The correct answer is: d.




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

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