Java puzzle 23: Inheritance, animal example

<< 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 Meat to the standard output.
Wrtie only one statement at line 11 of the class WildAnimal. As a result of adding your statement, the program writes “Wolf 50.0 Meat” to the standard output. What is that statement?

Note: The classes Animal and WildAnimal are two separate file in the same package.

Java puzzle 23: Inheritance, animal example

Level: Normal

Animal.java

public class Animal
{
  String name;
  double speed;
  
  void printData()
  {
    System.out.print(name + " ");
    System.out.print(speed + " ");
  }
}

WildAnimal.java

public class WildAnimal extends Animal
{
  String food;
  
  WildAnimal(String food)
  {
    this.food = food;
  }
  void printData()
  {
    // add your statement here!
    System.out.print(food + " ");
  }
  public static void main(String[] args)
  {
    WildAnimal wa = new WildAnimal("Meat");
    wa.name = "Wolf";
    wa.speed = 50.00;
    wa.printData();
  }
}
Author: Sar Maroof

Answer explanation

  1. The statements wa.name and wa.speed assign the values wolf and 50.00 to the variables name and speed respectively.
  2. The method printData() inside the class WildAnimal writes only the value of the variable food to the standard output.
  3. To write the values of the variable name and the variable speed to the standard output we need to invoke the method printData() inside the superclass Animal.The answer is: super.printData();

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!
SarMaroof.com 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 *

Sarmaroof © 2017