In: Computer Science
Define a class to represent a Temperature. Your class should contain
The code for the given problem statement is given below. Since programming language is not mentioned so Java is used to implement. All the steps are given in comments and output is given. It has class Temperature which has two methods. toCelsius is used to convert Fahrenheit to celcius and returns Celsius value and equals compares two objects and returns true if both objects are equal.
//Code starts here
//This class Temperature has two methods : Convert Fahernheit to
Celcius and to compare Objects
public class Temperature
{
int fahrenheit; //Instance variable to store
Fahernheit temperature
public Temperature(int fahrenheit){ //parameterized
constructor
this.fahrenheit = fahrenheit;
}
public double toCelsius(){ //Member method to calculate the
equivalent temperature in Celsius unit with decimal value.
double celsius= (((double)this.fahrenheit - 32) * 5/9)/100 * 100;
//Conversion formula from Fahernheit to Celsius
return celsius; //return Celsius temperature
}
public boolean equals(Object obj){ //Method definition to override
the equals() method. It compares objects
if(obj == this) //If object is compared with itself return
true
return true;
if(!(obj instanceof Temperature)) // If given object is not
instance of Temperature class return false
return false;
Temperature temperature = (Temperature) obj; // Otherwise convert
object to temperature object and compare
return (fahrenheit == temperature.fahrenheit); //return true if
fahrenheit temperature are same otherwise false
}
public static void main(String[] args) {
Temperature t = new
Temperature(43); //First object of Temperature class
System.out.println("42 in
Fahrenheit is equal to : " + t.toCelsius() + " Celsius"); //Call
toCelsius method to convert Fahernheit to Celsius
Temperature t2 = new
Temperature(42); //Second object of Temperature class
System.out.println("Are objects
equal?");
System.out.println(t.equals(t2));
//Call equals method to compare two objects
}
}
//Code ends here
Output