Constructor questions

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Constructor questions

thatwillchaiguy
Hi, I am new to both Java and Jack. I am confused with constructors.

Say, in Java, I wrote:

public class Point {
      private int x, y, z;

      public Point(int aX, int aY, int aZ) {
            x = aX;
            y = aY;
            z = aZ;
      }

      public Point() {
            this (0,0,0)
      }
}

and in Jack, I wrote:

class Point3D {

        static int x, y, z;

        constructor Point3D new(int aX, int aY, int aZ)
        {
             let x = aX;
             let y = aY;
             let z = aZ;
        }

        constructor Point3D new()
        {
             let x = 0;
             let y = 0;
             let z = 0;
        }
}


Are these two equivalent? If not, how do I code the default constructor (0,0,0) in Jack?


     
Reply | Threaded
Open this post in threaded view
|

Re: Constructor questions

ashort
This post was updated on .
(1) Don't use "static". Use "field".  

Field variables are specific to the instance of the class.  You want this because you might have many points to keep track of, each with their own x, y, and z coordinates.

(2) constructors must call

     return this;

typically after all the let statements where you assign values to the fields.

(3) you can't have 2 constructors called "new", even if one takes args and the other does not. Just give the one with args a different name.  [At least this is the way Jack is defined. If you want to support this, you'll have to give your compiler the ability to handle it.]



Reply | Threaded
Open this post in threaded view
|

Re: Constructor questions

ivant
In reply to this post by thatwillchaiguy
thatwillchaiguy wrote
Are these two equivalent? If not, how do I code the default constructor (0,0,0) in Jack?
To add to ashort's answer, you can do the "default" constructor like this:
    constructor Point3D new0() {
        return Point3D.new(0, 0, 0);
    }
Reply | Threaded
Open this post in threaded view
|

Re: Constructor questions

ashort
Having a constructor return the value from another constructor is commonly done in other languages, but the built-in Jack compiler does not support it - it really does want "return this;" inside of every constructor.  Of course, the compiler you build doesn't have to check for this, but it might irritate you that the built-in compiler will consistently fail.