使用构造函数语句(构造函数?) [英] using a Constructor statement (constructor?)

查看:318
本文介绍了使用构造函数语句(构造函数?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触Java,所以我相信这是一个简单的问题(我的脑袋从研究整天旋转)。这里是我学习的代码,不记得/找出这行代码是做什么:

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.

这是自上而下的代码:

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

...

推荐答案

是的!

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

是一个构造函数。

基本上, new Temperature对象并通过以下方式设置类中的一些字段:

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)检查类型 C c F f K k


2)适当调用方法:
setDegreesCelsius(degrees); setDegreesFahrenheit ); setDegreesKelvin(degrees); 个别。

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:

如果输入 C

类似地, c> c> 如果 F degreesFahrenheit; ,如果 K degreesKelvin;

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

希望这有帮助。

在您的评论后更新

public Temperature(String type,double degrees)构造函数只接受2个争论。 a String double 。有这样,你可以创建一个 Temperature 实例,并设置一些字段的值。

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.

此代码:

温度x =新温度(C,35); 表示 x 是一个温度对象,在Celcious刻度中计数,当前温度为35℃。

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.

希望这更有意义

这篇关于使用构造函数语句(构造函数?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆