Week 5 Notes and Questions

Strings, Object, subclassing

Java lesson object, toString

Questions

  1. Write a "Car" class, which contains fields for fuel tank size and mpg, and which has a method "getRange()" to compute range based on mpg/tank capacity.
  2. Write a "Garage" class that contains two "Car" objects - one for Carl and one for Mrs. Carl. Provide a method for the "Garage" class which tells you the largest range of any car in the Garage.
  3. Write a "PeopleCarrier" subclass of Car which modifies "range" to be determined partly by number of people being carried.
  4. Write another class which creates a new "Garage" and puts two PeopleCarriers in it. Prove that when you ask "Garage" which has the largest range, the "PeopleCarrier.getRange()" method is called.
  5. Make the definition of your "Garage" class look like this:
           public abstract class Garage {
               . . .
           }
    
    What difference does this make?
  6. Try and think of a better example than mine!
  7. What method have you implemented in all your classes (assuming you followed the advice above)?
  8. If all classes are extensions of "Object", what methods do you think should be part of Object? Look in the documentation and see what there actually is.
  9. especially for Julian Assuming you have modified your "Person" class to include a "toString" method, so that the following code:
        Person me = new Person("nick",21);             // 1
        System.out.println("the person is " + me);     // 2
    
    displays something like:
        the person is nick, who is 21 and was created on xxxxx
    

    Can you come up with a way to change the code at "2" (you can change the line or add extra lines, but not change any of the "Person" class methods) so that the output will now be:

       the person is Person@1bab50a
    
    i.e. bypass the "Person.toString()" method?
  10. especially for Martin The following code:
            int x = 123;
    	System.out.println("x is -->" + x + "<--");
    
    will by default output:
    x is -->123<--
    
    What can you do (if anything) to make the integer value be padded up to eight digits with leading zeroes? i.e.:
    x is -->00000123<--
    

Back to index page