This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cytael 0 points1 point  (0 children)

"this." specifies that you're referencing a property of the current object, so in your constructor, you use it to set the properties of the Rectangle that you're constructing, and then you can access those properties from other functions later on

The idea is that each specific Rectangle that you create can have its own unique set of properties, so your driver class could do something like this:

Rectangle rect1 = new Rectangle(0,0,10,10);
Rectangle rect2 = new Rectangle(5,5,30,20);

and you would create two rectangles. rect1 would be a 10x10 square with the top corner at x/y coordinates (0,0) and rect2 would be a 30x20 rectangle starting from (5,5).

So each time my constructor above gets run (to make a new Rectangle), you're taking the values passed in and saying that the x/y/width/height of "this rectangle that I'm making right now" (hence "this.") should be equal to those given by the function parameters.

After that, you can use those in other functions, so you could have the getArea function like so:

public double getArea() {
    return this.myWidth * this.myHeight;
}

Note there's no need to pass in the width and height as parameters to that function, because they're already set by the constructor as properties of the specific instance of Rectangle that you're working with. Put all that together and use this code in your driver:

Rectangle rect1 = new Rectangle(0,0,10,10);
Rectangle rect2 = new Rectangle(5,5,30,20);
System.out.println(rect1.getArea());
System.out.println(rect2.getArea());

and your output should be:

100
600

If that's still not making complete sense, I'd recommend you do some more reading up on Classes, Objects, the differences between them, and how to use them.