简体   繁体   English

需要一些帮助来理解教程代码:Java - Class Constructors / Initializers

[英]Need some assistance understanding tutorial code: Java - Class Constructors / Initializers

I've been following some basic Java tutorials on Pluralsight, I've hit a point where I don't quite understand what the tutor is trying to explain, he seems to have a tendency to quickly go over some exercises rather quickly and it's a little difficult to follow.我一直在关注 Pluralsight 上的一些基本 Java 教程,我遇到了一个问题,我不太明白导师想要解释的内容,他似乎倾向于很快地复习一些练习,这是一个有点难以遵循。

I have 2 classes, a "Main" and a "MathExecution".我有 2 个类,一个“Main”和一个“MathExecution”。 I fully understand what is happening in MathExecution, however I don't quite understand some aspects of Main, which I will go over.我完全了解 MathExecution 中发生的事情,但是我不太了解 Main 的某些方面,我将对其进行介绍。 I will paste both classes below:我将在下面粘贴两个类:

Main.java:主.java:

public class Main {

    public static void main(String[] args) {

//        double[] value1 = {100.0d, 18.0d, 30.0d,  27.0d};
//        double[] value2 = {50.0d, 2.0d, 15.0d, 99.0d};
//        char[] opCodes = {'d', 'm', 's', 'a'};
//        double[] result = new double [opCodes.length];

        MathEquation[] equations = new MathEquation[4];
        equations[0] = create(100.00d, 50.0d, 'd');
        equations[1] = create(25.0d, 92.0d, 'a');
        equations[2] = create(225.0d, 17.0d, 's');
        equations[3] = create(11.0d, 3.0d, 'm');


        for (MathEquation equation: equations){
            equation.execute();
            System.out.print("Result: ");
            System.out.println(equation.getResult());
        }

    }

    public static MathEquation create(double value1, double value2, char opCode){
        MathEquation equation = new MathEquation();
        equation.setValue1(value1);
        equation.setValue2(value2);
        equation.setOpCode(opCode);

        return equation;
    }
}

MathExecution.java: MathExecution.java:

public class MathEquation {


    private double value2;
    private double value1;
    private char opCode;
    private double result;

    public double getValue1() {return value1;}
    public double getValue2() {return value2;}
    public double getOpCode() {return opCode;}
    public double getResult() {return result;}

    public void setValue1(double value1) {this.value1=value1;}
    public void setValue2(double value2) {this.value2=value2;}
    public void setOpCode(char opCode) {this.opCode=opCode;}






    public void execute(){

        switch (opCode){
            case 'd':
                result = value2 != 0.0d ? value1 / value2: 0.0;
                break;

            case 'm':
                result = value1 * value2;
                break;

            case 's':
                result = value1 - value2;
                break;

            case 'a':
                result = value1 + value2;
                break;

            default:
                System.out.println("Something Broke!");
                result = 0.00d;
                break;
        }

    }
}

I don't quite understand (I don't think I do anyway) what's actually going on here:我不太明白(我认为我无论如何都不明白)这里实际发生了什么:

 MathEquation[] equations = new MathEquation[4];

When looking at it, I assume we're creating a new instance of MathEquation, calling is "equations" and specifying that we're going to pass 4 arrays (which we do later).在查看它时,我假设我们正在创建 MathEquation 的一个新实例,调用是“equations”并指定我们将传递 4 个数组(我们稍后会这样做)。

I'm going to skip ahead a little...我要跳过一点...

I don't quite understand what's happening here:我不太明白这里发生了什么:

public static MathEquation create

I understand I'm declaring a method (?), it's public, meaning it can be accessed from anywhere (?), I don't know what static means yet.我知道我正在声明一个方法(?),它是公共的,这意味着它可以从任何地方访问(?),我还不知道静态是什么意思。 It's being called "create" but I don't know what part MathEquation plays in this declaration.它被称为“创建”,但我不知道 MathEquation 在此声明中的作用。

I think I understand what's going on in the body of this method,我明白这个方法的主体发生了什么,

MathEquation equation = new MathEquation();
equation.setValue1(value1);
equation.setValue2(value2);
equation.setOpCode(opCode);

return equation;

We're creating another instance of MathEquation and calling it equation.我们正在创建 MathEquation 的另一个实例并将其称为方程。 Then passing the parameters specified when declaring "create".然后传递声明“create”时指定的参数。

I don't think I understand how the return statement works fully, why is it returning the whole class (equation)?我想我不明白 return 语句是如何完全工作的,为什么它返回整个类(方程)?

Looking at the "for" loop.查看“for”循环。 I see it uses the "equation" that was previously returned but I don't understand the syntax here:我看到它使用了之前返回的“方程”,但我不明白这里的语法:

MathEquation equation: equations

I think I understand the final line..我想我明白最后一行了..

System.out.println(equation.getResult());

We're just printing getResult which is just a public method in the MathExecution class, it returns the value of a private variable.我们只是打印 getResult ,它只是 MathExecution 类中的一个公共方法,它返回一个私有变量的值。

I would really appreciate it if anyone could please provide a little insight into what's going on.如果有人可以对正在发生的事情提供一些见解,我将不胜感激。 I've rewatched the video and tried to play around with the code but I can't seem to understand how this connects together.我重新观看了视频并尝试使用代码,但我似乎无法理解它是如何连接在一起的。

Alternatively, if you could point me at any resources where I could perhaps gain a better understanding before coming back to this example, that would also be perfect.或者,如果您能在回到本示例之前向我指出我可能会获得更好理解的任何资源,那也将是完美的。

Thank you very much for reading.非常感谢您的阅读。

Here are my answers:以下是我的回答:

  1. Array Creation数组创建

I don't quite understand (I don't think I do anyway) what's actually going on here:我不太明白(我认为我无论如何都不明白)这里实际发生了什么:

MathEquation[] equations = new MathEquation[4];

When looking at it, I assume we're creating a new instance of MathEquation,在查看它时,我假设我们正在创建 MathEquation 的新实例,

No, the code creates an array of four references, and calls that array equations .不,代码创建了一个包含四个引用的数组,并调用该数组equations One object is created (the array) and its indexes are all set to null .创建了一个对象(数组),其索引都设置为null

  1. Method declarations方法声明

I don't quite understand what's happening here:我不太明白这里发生了什么:

public static MathEquation create

I understand I'm declaring a method (?), it's public, meaning it can be accessed from anywhere (?), I don't know what static means yet.我知道我正在声明一个方法(?),它是公共的,这意味着它可以从任何地方访问(?),我还不知道静态是什么意思。

This is super basic, you should read the tutorial again.这是非常基础的,你应该再次阅读教程。 static means the method (or field) is not attached to any instance of the class. static意味着该方法(或字段)未附加到该类的任何实例。 Instead it is common (global) to all objects in the system.相反,它对系统中的所有对象都是通用的(全局)。 The MathEquation is the return type of the method: it returns one MathEquation object. MathEquation是该方法的返回类型:它返回一个MathEquation对象。

  1. Method invocation方法调用

This stuff here is also super basic, it's just calling a method.这里的东西也是超基础的,就是调用一个方法而已。

MathEquation equation = new MathEquation();
equation.setValue1(value1);
equation.setValue2(value2);
equation.setOpCode(opCode);

return equation;

We're creating another instance of MathEquation and calling it equation.我们正在创建 MathEquation 的另一个实例并将其称为方程。 Then passing the parameters specified when declaring "create".然后传递声明“create”时指定的参数。 I don't think I understand how the return statement works fully, why is it returning the whole class (equation)?我想我不明白 return 语句是如何完全工作的,为什么它返回整个类(方程)?

Creating another instance of MathEquation is correct.创建MathEquation另一个实例是正确的。 Passing parameters... OK, it is, but more simply it's just calling methods on the object just created.传递参数...好吧,它是,但更简单地说,它只是在刚刚创建的对象上调用方法。 It is using the parameters that were given when create was invoked, sure.当然,它使用的是在调用create时给出的参数。 The return statement only has the option of returning a "whole class" or a primitive (like int or char ) so that's the only choice you have. return 语句只能选择返回“整个类”或原始类型(如intchar ),因此这是您唯一的选择。 Really it returns the "whole object" by just returning the reference to the whole object.实际上,它仅通过返回对整个对象的引用来返回“整个对象”。

  1. For-each对于每个

Looking at the "for" loop.查看“for”循环。 I see it uses the "equation" that was previously returned but I don't understand the syntax here:我看到它使用了之前返回的“方程”,但我不明白这里的语法:

MathEquation equation : equations

That's just a for-each loop, read the docs: https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html这只是一个for-each循环,阅读文档: https : //docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

  1. Printing stuff打印的东西

I think I understand the final line..我想我明白最后一行了..

System.out.println(equation.getResult());

We're just printing getResult which is just a public method in the MathExecution class, it returns the value of a private variable.我们只是打印 getResult ,它只是 MathExecution 类中的一个公共方法,它返回一个私有变量的值。

Correct.正确。

I will try to explain it in simple words.我将尝试用简单的语言来解释它。 If you find a word that you do not know or understand, look it up in the Java Tutorials .如果您发现不认识或不理解的单词,请在Java 教程 中查找。


As a basis, we will look at the create method first.作为基础,我们将首先查看create方法。 What the first line (the signature) says, is that you have a method that can be called from anywhere ( public ), does not need an instance to call it ( static , I think you should jsut look up the definition , I can not come up with an easy explanation right now), returns you a MathEquation , is called create , and needs three parameters as input to create that return value.第一行(签名)说的是,你有一个可以从任何地方( public )调用的方法,不需要一个实例来调用它( static ,我认为你应该查一下定义,我不能现在想出一个简单的解释),返回一个MathEquation ,称为create ,并且需要三个parameters作为输入来创建该返回值。

public static MathEquation create(double value1, double value2, char opCode)

The method then proceeds:然后该方法继续:

    // take the MathEquation class and create an instance by using the constructor
    MathEquation equation = new MathEquation();

    // give the equation the necessary values it needs to be executed later
    equation.setValue1(value1);
    equation.setValue2(value2);
    equation.setOpCode(opCode);

    // return that equation to the caller of the method for them to use
    return equation;
}

Ok, so what is going on in the main method?好的,那么 main 方法中发生了什么?

First, we create an array (which is kind of a list) that has room for 4 MathEquation s and is called equations .首先,我们创建一个数组(它是一种列表),其中有 4 个MathEquation的空间,称为equations It is empty at the moment!此刻是空的!

    MathEquation[] equations = new MathEquation[4];

That's why we have to fill it here.这就是为什么我们必须在这里填写它。 We use the create method from above to get 4 instances of MathEquation and put them in the empty slots (0-3) of our array.我们使用上面的create方法获取MathEquation 4 个实例并将它们放入数组的空槽 (0-3) 中。

    equations[0] = create(100.00d, 50.0d, 'd');
    equations[1] = create(25.0d, 92.0d, 'a');
    equations[2] = create(225.0d, 17.0d, 's');
    equations[3] = create(11.0d, 3.0d, 'm');

Afterwards we take our array, use a for loop to look at each equations in it, and do stuff.然后我们取出数组,使用for循环查看其中的每个方程,然后做一些事情。 The for loop reads as follows: "for each equation in equations" for循环如下:“对于方程中的每个方程”

    for (MathEquation equation: equations) {

And for equation, we ask it to solve itself.对于方程,我们要求它自行求解。 This will store the result inside teh equation object.这会将结果存储在等式对象中。 We then asl the equation for that result and print it to the console.然后我们为该结果获取等式并将其打印到控制台。

        equation.execute();
        System.out.print("Result: ");
        System.out.println(equation.getResult());

When looking at it, I assume we're creating a new instance of MathEquation, calling is "equations" and specifying that we're going to pass 4 arrays (which we do later).在查看它时,我假设我们正在创建 MathEquation 的一个新实例,调用是“equations”并指定我们将传递 4 个数组(我们稍后会这样做)。

No, you're actually creating a single array with 4 items.不,您实际上是在创建一个包含 4 个项目的数组。 It doesn't create any instances of MathEquation (or any of the items in the array) - you just create the array.它不会创建MathEquation任何实例(或数组中的任何项目)——您只需创建数组。

Think about it this way: suppose I'm booking a group at a hotel.这样想:假设我在酒店预订一个团体。 I call the hotel and tell them that there will be 4 families coming in. The manager "sets aside" 4 rooms next to each other.我打电话给酒店,告诉他们将有 4 个家庭进来。经理“预留”了 4 个彼此相邻的房间。 Clearly, the manager "setting aside" the 4 rooms doesn't actually create the rooms or the families, and it doesn't cause the families to magically appear in the rooms.显然,经理“搁置”4 个房间实际上并没有创建房间或家庭,也不会导致家庭神奇地出现在房间中。 It merely says that, once the families arrive, the manager intends to put them there.它只是说,一旦这些家庭到达,经理打算将他们安置在那里。

An interesting feature of the fact that the families are next to each other: if you know which room the first family is in, you can immediately calculate which room the other families will be in, too.家庭彼此相邻这一事实的一个有趣特征是:如果您知道第一个家庭在哪个房间,您就可以立即计算出其他家庭也将在哪个房间。 For example, if Family 1 is in room 100, then clearly Family 2 must be in room 101, Family 3 must be in room 102, and Family 4 must be in room 103.例如,如果家庭 1 在 100 房间,那么显然家庭 2 必须在 101 房间,家庭 3 必须在 102 房间,家庭 4 必须在 103 房间。

Now, here's an analogy for static - suppose that the hotel chain has a web site that allows you to do bookings.现在,这里有一个static类比 - 假设连锁酒店有一个允许您进行预订的网站。 The web site is associated with the entire chain of hotels, not just that individual hotel.该网站与整个连锁酒店相关联,不仅仅是个别酒店。 This is kind of what static does - it's associated with the class (by analogy, the entire hotel chain), not just that particular object (or hotel).这就是static作用 - 它与类相关联(以此类推,整个连锁酒店),而不仅仅是那个特定的对象(或酒店)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM