Page 587 - Introduction to Programming with Java: A Problem Solving Approach
P. 587

                Exercises 553 Identify all compilation errors in this code fragment. Provide a compilation error message if you like, but
it’s not required.
Animal animal;
Dog fido, sparky = new Dog();
animal = sparky;
fido = new Animal();
7. [after§13.6]Supposeyouhaveanobjectcalledthing,butyouarenotsurewhattypeitis,andyouwould like to have your program print that type out. The Object class (and therefore any class!) has another method, getClass, that returns a special object of type Class that contains information about the class of the object calling the getClass method. The Class class has a method called getName which returns the name of the class described by its calling object. Write a statement that prints the name of thing’s class.
8. [after §13.7] Given: Animal 􏰁 superclass, Dog 􏰁 subclass, Cat 􏰁 subclass.
In the following code fragment, the bottom two lines generate compile-time errors. Provide corrected versions of those two lines. Preserve the spirit of the original code. For example, the bottom line should assign the second animals element into the fluffy variable.
Animal[] animals = new Animal[20];
animals[0] = new Dog();
animals[1] = new Cat();
Dog lassie = animals[0];
Cat fluffy = animals[1];
9. [after §13.8] Each abstract method in a superclass must be overridden by a corresponding method in Apago PDF Enhancer
every non-abstract class descended from it. (T/F).
10. [after §13.8] Given the Pets3 program below, write an abstract Animal2 class that contains just
one item—an abstract declaration for a speak method. Write Dog2 and Cat2 classes that extend Animal2, so that when you run the Pets3 program and input either a ‘c’ or a ‘d,’ the program prints either “Meow! Meow!” or “Woof! Woof.”
import java.util.Scanner;
public class Pets3
{
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
Animal2 animal;
System.out.print("Which type of pet do you prefer?\n" +
"Enter c for cats or d for dogs: ");
if (stdIn.nextLine().charAt(0) == 'c')
{
}
else
{
}
animal = new Cat2();
animal = new Dog2();
animal.speak();
} // end Pets3 class




























































   585   586   587   588   589