Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to Java, so I'm sure this is an easy question (my head is spinning from studying all day long). Here's the code I'm studying and can't remember/figure out what this line of code is doing:

public Temperature(String type, double degrees) { 
if (type.equalsIgnoreCase("C"))

Is this considered a constructor? What are the two parameters "String type, double degrees" doing? tia.

Here's the code from the top down:

public class Temperature { 
private double degreesFahrenheit; // Fahrenheit temperature
private double degreesCelsius; // Celsius temperature 
private double degreesKelvin; // Kelvin temperature

/** * This constructor for Temperature sets the temperature 
*   values to the value from degrees, based on the type * 
* @param type temperature scale to use 
* @param degrees degrees Fahrenheit 
*/ 

public Temperature(String type, double degrees) { 
if (type.equalsIgnoreCase("C"))
setDegreesCelsius(degrees); 
else if (type.equalsIgnoreCase("F")) setDegreesFahrenheit(degrees);
else if (type.equalsIgnoreCase("K")) setDegreesKelvin(degrees);

...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes! This:

public Temperature(String type, double degrees){
    ...
} 

is a constructor.

Basically what it does when called is to create a new Temperature object and set some fields in the class by:

1) Check if the arguement type is C or c, F or f, K or k and

2) appropriatelly call the methods:
setDegreesCelsius(degrees); , setDegreesFahrenheit(degrees); and setDegreesKelvin(degrees); respectivelly.

You haven't posted the code for those methods but its most likely that:

if the input is C you assign degreesCelsius; the value of the degree arguement of your constructor.

Similarly if F to the degreesFahrenheit; and if Kto the degreesKelvin;

The definition of these methods probably looks like this:

setDegreesCelsius(double degrees){
    this.degreesCelsius = degrees;
}

Hope this helps.

Update after your comment:

public Temperature(String type, double degrees) that the constructor only accepts 2 arguements. a String and a double. There are there so that you can create a Temperature instance and also set the values of some fiels.

For example this code :

Temperate x = new Temperature("C", 35); means that x is a Temperature object and counts in the Celcious scale, and the current temperature is 35.

Hope this makes more sense


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...