Object-Oriented Programming/Properties/Java

From Wikiversity
Jump to navigation Jump to search

Main.java[edit | edit source]

/** This program demonstrates use of the Temperature class. **/

public class Main{
    public static void main(String[] args){
        var temperature = new Temperature();
        temperature.setCelsius(37);
        System.out.println(temperature.getFahrenheit());

        temperature = new Temperature();
        temperature.setFahrenheit(98.6);
        System.out.println(temperature.getCelsius());

        temperature = new Temperature();
        System.out.println(temperature.toCelsius(98.6));
        System.out.println(temperature.toFahrenheit(37));
    }
}

Temperature.java[edit | edit source]

/** Temperature converter. Provides temperature conversion functions. Supports Fahrenheit and Celius temperatures.

Examples:

    Temperature temperature = new Temperature();
    temperature.setCelsius(37);
    System.out.println(temp.getFarenheit());

    temperature = new Temperature();
    temperature.setFahrenheit(98.6);
    System.out.println(temp.getCelcius());

    temperature = new Temperature();
    System.out.println(temp4.toCelsius(98.6));
    System.out.println(temp4.toFahrenheit(37));

**/

public class Temperature {
    private double _celsius;
    private double _fahrenheit;

    // Returns Celsius value.
    public double getCelsius() {
        return this._celsius;
    }

    // Sets Celsius value.
    public void setCelsius(double value) {
        this._celsius = value;
        this._fahrenheit = this.toFahrenheit(value);
    }

    // Returns Fahrenheit value.
    public double getFahrenheit() {
        return this._fahrenheit;
    }

    // Sets Celsius value.
    public void setFahrenheit(double value) {
        this._fahrenheit = value;
        this._celsius = this.toCelsius(value);
    }

    // Converts Fahrenheit temperature to Celsius.
    public double toCelsius(double farenheit) {
        return (farenheit - 32) * 5.0 / 9.0;
    }

    // Converts Celsius temperature to Fahrenheit.
    public double toFahrenheit(double celsius) {
        return celsius * 9.0 / 5.0 + 32;
    }
}

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.

See Also[edit | edit source]