Java puzzle 21: Using inheritance

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   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

MySuper.java

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

MySub.java

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

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);





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 *