using a Constructor statement (constructor?)

我与影子孤独终老i 提交于 2019-12-13 09:31:08

问题


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);

...


回答1:


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



来源:https://stackoverflow.com/questions/25775088/using-a-constructor-statement-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!