/* --- CSU213 Fall 2006 Lecture Notes --------- Copyright 2006 Viera K. Proulx Lecture 14: October 5, 2006 Overloading Constructors */ /* 1. Define the class that represent temperature. Being in the USA we assume the temperature is given in Fahrenheit. If the given temperature is below -100 make it 100 If it is above +150 make it 150. */ /* +----------+ | Temp | +----------+ | double t | +----------+ */ // to represent a temperature reading class Temp { double t; // the temperature measured in Fahrenheit // the primary constructor Temp(double t) { if (t < -100) this.t = -100; else if (t > 150) this.t = 150; else this.t = t; } /* Now add a constructor that takes a number and a character C or F to record the temperature. */ Temp(double t, char fc){ this(t); if ((fc == 'C') || (fc == 'c')) this.t = this.t * 9 / 5.0 + 32; } /* Then add methods that produce the temperature in C or in F or as a String with C or as a String with F */ // provide the temperature in Centigrades double getTempC(){ return (this.t - 32) * 5 / 9; } // provide the temperature as a String String asString(){ return String.valueOf(Math.round(this.t) + " F"); } } class Examples { Examples () {} Temp f20a = new Temp(20.0); Temp f20b = new Temp(20); Temp f20c = new Temp(20.0, 'F'); Temp f20d = new Temp(20.0, 'C'); Temp f20e = new Temp(20, 'F'); Temp f20f = new Temp(20, 'c'); Temp f20g = new Temp(20.0, 'f'); // test the method getTempC boolean testGetTempC = (check this.f20a.getTempC() expect -6.666 within 0.01) && (check (new Temp(32)).getTempC() expect 0.0 within 0.01) && (check (new Temp(-40)).getTempC() expect -40.0 within 0.01) && (check (new Temp(0, 'c')).getTempC() expect 0.0 within 0.01); // test the method asString boolean testAsString = (check this.f20a.asString() expect "20 F"); }