9

Hello i'm still kind of new to java.. I get the concept of "this" when it comes to instance variables but when i use it in a constructor with no parameters i get a little confused. So my question is how does something like this work?

private double x; private double y; public static final double EPSILON = 1e-5; public static boolean debug = false; public Point(double x, double y){ this.x=x; this.y=y; // Done sets the x,y private types to the x,y type provided in the () } public Point(){ this(0.0,0.0); //Sets, x and y to doubles of 0.0,0.0?? } //How does this work? 

Would my point() constructor create an origin of (0.0,0.0) by calling the point (x,y) constructor? Any clarification on this would help me out a lot!

1
  • 1
    "Would my point() constructor create an origin of (0.0,0.0) by calling the point (x,y) constructor?" - Yes, that's the point. this(...) allows you to chain constructor calls together to insure the state of the object when it is created Commented Jun 25, 2014 at 2:21

3 Answers 3

7

this(arguments) is a special syntax only available inside constructors. What it does is call a another constructors with the given arguments. So calling this(0.0, 0.0) will invoke the constructor Point(double, double) with the values (0.0, 0.0). This, in turn, will set x and y to 0.0.

Sign up to request clarification or add additional context in comments.

Comments

1

When calling this(), you redirect the call of that constructor to another constructor (in this case the first constructor). So you create a Point (0,0).

You basically states that whenever one calls new Point(), it is replaced by Java with new Point(0.0,0.0)


It can sometimes be useful to do the opposite (call a constructor with less parameters). In that case each constructor simply handles its additional parameters which is more oriented to "separation of concerns".

For instance:

public class Point { private double x = 0.0d; private double y = 0.0d; public Point () { } public Point (double x) { this(); this.x = x; } public Point (double x, double y) { this(x); this.y = y; } } 

Comments

0

Poine() will init x and y with 0.0

Point(double x, double y) will init x and y with x and y in the params of the function.

this in Point(double x, double y) was a pointer of the Point class

this in Point() you can see as a Constructor for the Point class , it will

call Point(double x , double y).

Comments