Java puzzle 21: Using inheritance

<< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
 P01   P02   P03   P04   P05   P06   P07   P08   P09   P10   P11   P12   P13   P14   P15   P16   P17   P18   P19   P20   P21   P22   P23   P24 
 By title 

If this code is compiled and run, it writes 5, 6 to the standard output.
Write only one statement at line 8 of the class MySub. As a result of that the program writes 2, 7 to the standard output. What is that statement?

Note: The classes MySuper and MySub are two separate files in one package.

Java puzzle 21: Using inheritance

Level: Normal

public class MySuper
  int x = 5;
  int y = 6;
  MySuper(){ }
  MySuper(int x, int y)
    this.x = x;
    this.y = y;

public class MySub extends MySuper
  int x = 5;
  int y = 6;
    // add your statement here
  public static void main(String[] args)
    MySuper ms = new MySub();
    System.out.print(", ");

Author: Sar Maroof

Answer explanation

  1. By casting a superclass object to a subclass type reference.
  2. The variables of the object ms depend on the reference of the object.
  3. By invoking the 2-argument constructor of the MySuper class, we can reassign the values of x and y.

The correct answer is: super(2, 7);

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” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked 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 *

Sarmaroof © 2017