import java.text.DecimalFormat; public class Length { // fields(usually private) private DecimalFormat F = new DecimalFormat("#.00"); private double value; private String unit; private boolean isValid = true; // constructor (almost always public) public Length(double value, String unit) { this.value = value; this.unit = unit; if (!((unit.equals("meter")) || (unit.equals("feet")))) isValid = false; } // methods (usually public) public void display() { if (isValid) System.out.println(F.format(value) + " " + unit); else System.out.println("invalid length"); } // return a new length which is the old one converted // to meter public Length convertToMeter() { if ((isValid) && (unit.equals("feet"))) return new Length(value / 3.2809, "meter"); else return this; } public Length convertToFeet() { if ((isValid) && (unit.equals("meter"))) return new Length(value * 3.2809, "feet"); else return this; } // adds two lengths by first converting them to meters, // thus making the answer meters, too. Length add(Length l) { Length l_meter = l.convertToMeter(); Length meter = this.convertToMeter(); return new Length(meter.value + l_meter.value, "meter"); } }