Here's one way to do it:
public class Car { float tankSize; float mpg; public Car(float tankSize, float mpg) { this.tankSize = tankSize; this.mpg = mpg; } public float getRange() { return (mpg * tankSize); } public toString() { return "Car with mpg=" + mpg + ", tankSize=" + tankSize; } }
public class Garage { Car husbandsCar; Car wifesCar; public Garage(Car husband, Car wife) { husbandsCar = husband; wifesCar = wife; } public float maxRange() { float h = husbandsCar.getRange(); float w = wifesCar.getRange(); if (h > w) { return h; } return w; } public toString() { return "Garage with " + husbandsCar + " and " + wifesCar; } }
public class PeopleCarrier extends Car { int numPassengers; public PeopleCarrier(float tankSize, float mpg, int numPassengers) { // We can use the constructor in "Car" by using the "super" keyword super(tankSize,mpg); this.numPassengers = numPassengers; } public float getRange() { // Work out the "standard" range, use the "super" keyword again... float carRange = super.getRange(); // If there are a lot of passengers, halve it if (numPassengers > 4) { carRange = carRange / 2; } return carRange; } public toString() { return "PeopleCarrier with mpg=" + mpg + ", tankSize=" + tankSize + " with " + numPassengers + " passengers"; } }
public class UseGarage { public static void main(String[] args) { PeopleCarrier p1 = new PeopleCarrier(10,20,4); System.out.println("p1 has a range of " + p1.getRange()); PeopleCarrier p2 = new PeopleCarrier(10,20,8); System.out.println("p2 has a range of " + p2.getRange()); Garage g = new Garage(p1,p2); System.out.println("The biggest range in the garage is " + g.maxRange()); } }One way to confirm that the correct "getRange" method is called is to put a "println" in it...
public abstract class Garage { . . . }What difference does this make?
Garage g = new Garage(p1,p2);then you'll get an error saying "Garage is abstract; cannot be instantiated"
Person me = new Person("nick",21); // 1 System.out.println("the person is " + me); // 2displays 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@1bab50ai.e. bypass the "Person.toString()" method?
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<--
public class Martin { public static void main(String[] args) { int x=123; System.out.println("x is -->" + x + "<--"); java.text.DecimalFormat df = new java.text.DecimalFormat(); df.setMinimumIntegerDigits(8); df.setGroupingSize(0); System.out.println("with leading zeros, x is -->" + df.format(x) + "<--"); } }