简体   繁体   中英

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.

I have 2 classes, a "Main" and a "MathExecution". I fully understand what is happening in MathExecution, however I don't quite understand some aspects of Main, which I will go over. I will paste both classes below:

Main.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:

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

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.

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. Then passing the parameters specified when declaring "create".

I don't think I understand how the return statement works fully, why is it returning the whole class (equation)?

Looking at the "for" loop. 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.

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,

No, the code creates an array of four references, and calls that array equations . One object is created (the array) and its indexes are all set to 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. 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.

  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. Then passing the parameters specified when declaring "create". I don't think I understand how the return statement works fully, why is it returning the whole class (equation)?

Creating another instance of MathEquation is correct. 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. 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. Really it returns the "whole object" by just returning the reference to the whole object.

  1. For-each

Looking at the "for" loop. 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

  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.

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 .


As a basis, we will look at the create method first. 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(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?

First, we create an array (which is kind of a list) that has room for 4 MathEquation s and is called 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.

    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. The for loop reads as follows: "for each equation in equations"

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

No, you're actually creating a single array with 4 items. It doesn't create any instances of MathEquation (or any of the items in the array) - you just create the array.

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. 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. 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.

Now, here's an analogy for static - suppose that the hotel chain has a web site that allows you to do bookings. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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