Exercises


Note

The solutions to these exercises are in Appendix B.

  1. Which of the following hierarchies illustrate a good understanding of the difference between classes and objects? Which ones represent mistaken understanding? The arrows mean "has subclass", so in option A, Shape Triangle means "class Shape has subclass Triangle".

    1. Shape Triangle RightTriangle

    2. GreatLiterature GreatPoem DivineComedy

    3. Planet Continent

    4. Person HeadOfState Emperor

    5. Person HeadOfState Emperor AugustusCaesar

  2. Which of the following classes have a no-args constructor?

    1. A)

      class A { }
    2. B)

      class B {   B() { } }
    3. C)

      class C {   C(int x) { } }
    4. D)

      class D {   D(int y) { }   D() { } } 
  3. Write the code for two classes. The first, called WaterBird, has a float variable called weight. The class has a single constructor that looks like this:

    WaterBird(float w) {   weight = w; }

    Compile this class. Now create the second class, called Duck, which extends WaterBird. Duck has no variables or methods, so it shouldn't take you long to write it. Will Duck compile? First, think about the issues involved. Then try to compile Duck and see if you were right.

  4. Write some code to demonstrate to yourself the chain of construction. Create an inheritance hierarchy of 4 classes. Give them any names you like. They don't have to have any data or methods, but each one should have a no-args constructor. These constructors should print out a line identifying the current class (something like "Constructing an instance of WaterBird"). Your main() method should construct a single instance of your lowest-level subclass. What is the output? Does it matter which class contains the main() method?

  5. Write some code to demonstrate inheritance polymorphism. Create a superclass class with 3 subclasses. The superclass should have a method that prints out a line identifying the current class (something like "I am a Monster"). Two of the subclasses should override this method to print out a different message (like "I am a Werewolf"). Give the superclass a main() method with an array of size 4, typed as the superclass (for example, Monster[] monsters = new Monster[4];). Your main() should populate the array with references to 4 objects, each with a different class, and then traverse the array, calling your method on each array component. What is the output? Does it matter which class contains the main() method?




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net