• Develop code for expressions that are self-referencing and determine the result of these expressions

Assignment


Last section we introduced a problem where a local variable would be used in lieu of the instance variable.

1
2
3
4
5
6
7
8
9
public int getWidth() {
    int width = 999;
    return width;   // 999 is returned
}

public static void main(String args[]) {
    Rectangle r1 = new Rectangle(100, 200);
    System.out.println(r1.getWidth());
}

There is a very easy fix for this where you use the keyword this to represent the current object.

1
2
3
4
5
6
7
8
9
public int getWidth() {
    int width = 999;
    return this.width;  // 100 is returned
}

public static void main(String args[]) {
    Rectangle r1 = new Rectangle(100, 200);
    System.out.println(r1.getWidth());
}

Using this is always advised because it removes ambiguity. width looks like a local variable, but this.width is clearly an instance variable.

Also, this can also be used as an argument. The area() method is designed to be static since I don’t necessarily need a Rectangle to exist to want to know the area.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Rectangle {
    private int width;
    private int height;

    // ... methods and constructors ...

    public static int area(Rectangle r) {
        return r.width * r.height;
    }

    public String toString() {
        return this.width + " x " + this.height + "\n" +
                "Area: " + area(this);
    }

    public static void main(String args[]) {
        Rectangle r1 = new Rectangle();
        System.out.println(r1);
    }
}

Of course, the method is designed to accept a Rectangle object, begging the question “couldn’t you have just made it non-static?” Asking that question online will take you down the comp science philosophy rabbit hole. The short answer is … eh.