Java quiz 40: Method overriding

<< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
 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()
  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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below! offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof


 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 *