Java:为什么我的变量不能传递给我的方法可用的构造函数?

Ben*_*ist 3 java methods class

所以我在main中声明了一些变量并创建了一个新对象; 将变量作为参数传递给构造函数.现在,当我在类中调用一个方法时,我会认为这些变量可以被方法访问,而不必将它们作为参数传递给它.这不是这样吗?

这是代码:

import java.util.Scanner;

public class Step2_lab11 {

    public static void main(String[] args) {

        final int TAO = 50;
        final double DELTA_MINUTES = 0.1;

        System.out.println("VINETS AVKYLNINGSTID \n");
        System.out.println("Ange vinets temperatur:");

        Scanner userIn = new Scanner(System.in);
        double wineTemp = userIn.nextDouble();

        System.out.println("Vinets önskade temperatur:");
        double preferredTemp = userIn.nextDouble();

        System.out.println("Kylens/frysens temperatur:");
        double chillTemp = userIn.nextDouble();

        WineChiller wineChiller = new WineChiller(wineTemp, preferredTemp, chillTemp);

    }

}
Run Code Online (Sandbox Code Playgroud)

这是WineChiller.java类:

public class WineChiller {

    public WineChiller(double wineTemp, double preferredTemp, double chillTemp) {
        getChillingTime();

    }

    public void getChillingTime() {

        while(wineTemp>preferredTemp)
        {
            elapsedTime += DELTA_MINUTES;
            double dT = (wineTemp - chillTemp) * DELTA_MINUTES  / TAO;
            wineTemp -= dT;
        }
        System.out.println(Math.round(elapsedTime));

    }

}
Run Code Online (Sandbox Code Playgroud)

为什么getChillingTime不能将wineTemp等解析为变量?

编辑添加:非常感谢指点家伙.但还有一个警告!说明似乎暗示WineChiller类应该只包含构造函数和方法getChillingTime,并且getChillingTime不应该带参数!作业文件中是否有拼写错误?

Luk*_*der 5

虽然这可能在Scala或Ceylon等语言中有用(见下文),但在Java中,您必须明确地将构造函数参数分配给实例变量.从而:

public class WineChiller {

    double wineTemp;
    double preferredTemp;
    double chillTemp;

    public WineChiller(double wineTemp, double preferredTemp, double chillTemp) {
        this.wineTemp = wineTemp;
        this.preferredTemp = preferredTemp;
        this.chillTemp = chillTemp;

        getChillingTime();
    }
Run Code Online (Sandbox Code Playgroud)

构造函数参数仅在构造函数的范围内可见.构造函数调用您的事实getChillingTime()无关紧要.如果希望它们在WineChiller实例范围内可见,则必须在该类中创建成员.然后,该类的所有方法都可以访问实例成员.

无论如何,我强烈建议你仔细阅读Java教程.这是一个:

http://docs.oracle.com/javase/tutorial

其他JVM语言的构造函数

我认为你主要是在努力解决Java的冗长问题,你必须将构造函数参数显式复制到实例字段以实现封装.其他语言更优雅地解决了这个问题,其中构造函数可以与类本身一起隐式定义.但是,它们仍将转换为与上述Java代码等效的内容.例如:

斯卡拉:

class Greeter(message: String) {
    def SayHi() = println(message)
}

val greeter = new Greeter("Hello world!")
greeter.SayHi()
Run Code Online (Sandbox Code Playgroud)

例如:http://joelabrahamsson.com/learning-scala-part-four-classes-and-constructors/

锡兰

class Point(Float x, Float y) { ... }
object origin extends Point(0.0, 0.0) {}
Run Code Online (Sandbox Code Playgroud)

示例来自:http://ceylon-lang.org/documentation/1.0/spec/html_single/

  • @Benjamin我认为指令试图强迫你使用字段(方法中没有参数强烈暗示这一点).这并不让我感到惊讶,因为对于面向对象的程序非常不熟悉的人会经常尝试通过功能需要完成其工作的每个方面.除非字段被豁免,否则阅读"不应该包含其他内容"和"没有功能参数"会使问题变得不可能.这也是一个奇怪的问题 (2认同)