Assume that two classes ‘Temperature’ and ‘Sensor’ have been defined. ‘Temperature’ has a constructor that accepts a double parameter. ‘Sensor’ has a method named ‘getReading’ which returns the sensor’s current reading (a double). Write a static method ‘create’ (that could be added to the ‘Temperature’ class) that accepts a ‘Sensor’ object. ‘create’ gets the value of the current reading of the ‘Sensor’ object, and returns a new ‘Temperature’ object that is based on this reading.

Language: Java

Challenge:

Assume that two classes ‘Temperature’ and ‘Sensor’ have been defined. ‘Temperature’ has a constructor that accepts a double parameter. ‘Sensor’ has a method named ‘getReading’ which returns the sensor’s current reading (a double). Write a static method ‘create’ (that could be added to the ‘Temperature’ class) that accepts a ‘Sensor’ object. ‘create’ gets the value of the current reading of the ‘Sensor’ object, and returns a new ‘Temperature’ object that is based on this reading.

SOLUTION:

Language: Java

Challenge:

Assume that two classes ‘Temperature’ and ‘Sensor’ have been defined. ‘Temperature’ has a constructor that accepts a double parameter. ‘Sensor’ has a method named ‘getReading’ which returns the sensor’s current reading (a double). Write a static method ‘create’ (that could be added to the ‘Temperature’ class) that accepts a ‘Sensor’ object. ‘create’ gets the value of the current reading of the ‘Sensor’ object, and returns a new ‘Temperature’ object that is based on this reading.

Solution:


public static Temperature create(Sensor sensor){
    double reading = sensor.getReading();
    return new Temperature(reading);
}