Java puzzle 23: Inheritance, animal example

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





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!

1 Comment

Add a Comment
  1. please I need java coding for fingerprint authentication

Leave a Reply

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