Overview
csc207-01-grader@grinnell.edu
Can we talk about problem 2 from the writeup?
I hope you discovered that (a) If you use a field name without
this
, and there no local variable or parameter with the same name, Java interprets it asthis.name
(b) If you use a field name withoutthis
and you have a local variable or parameter with the same name, Java interprets it as parameter or local variable.
This can lead to confusion for the reader. So we recommend that you always include
this
when referring to fields.
In C, if you use a name, the compiler checks for (a) a local variable or parameter, in which case it uses that, or (b) a global variable.
Java vs. C: Both look at local/param first, Java then goes to fields (which C does not have), C then goes to globals (which Java doesn’t really have).
What was happening with string literals and objects?
==
with objects means “same area of memory”.
obj1.equals(obj2)
uses the equals method ofobj1
Strings are objects in Java.
Identical string literals occupy the same area of memory.
The treatment of other strings is left more open in the Java standard. We have discovered that our Java compiler uses new memory for each string you read with
Scanner.next()
.
equals
methods?Suppose we decide that two cells are equal if their x
field is equal.
public class Cell {
int x;
public Cell(int x) {
this.x = x;
} // Cell(int)
public boolean equals(Cell other) {
return this.x == other.x;
}
public static void main(String[] args) {
PrintWriter pen = new PrintWriter(System.out, true);
Cell c1 = new Cell(1);
Cell c01 = new Cell(1);
Cell c2 = new Cell(2);
pen.println(c1.equals(c01));
pen.println(c1.equals(c2));
pen.println(c1.equals("1"));
} // main
} // class Cell
What’s happening here? For the first two examples, it appears that our
equals
method worked correctly. For the third, it makes no sense that
we were able to pass a string.
Note: Every class automaticaly gets a default equals(Object other)
method,
which is almost certainly this == other
.
c1.equals(c2)
- c2 is a Cell, I can use equals(Cell)
method.
c1.equals("1")
- c2 is not a Cell, must use the equals(Object)
method.
The ability to have multiple methods with the same name and different parameters is called “overloading”. We tend to overload constructors.
sqrt
. We can do “generic” math.sqrt
example, you need not do a loop for the other types.
E.g.,
BigInteger bi = new BigInteger(“12345678901234567890”);
double sqrt_bi = MathUtils.sqrt(bi);
pen.println(“The square root of “ + bi + “ ~= “ + sqrt_bi);
pen.println(sqrt_bi + “^2 = “ + (sqrt_bi * sqrt_bi));int
values vs. Integer
objectsint i = 1;
+---------+
i | 1 |
+---------+
Integer j = new Integer(2); // deprecated
+---------+ +Integer---+
j | *-----------> | val: 2 |
+---------+ +----------+
Integer k = 3; // Automatic conversion
+---------+ +Integer---+
k | *-----------> | val: 3 |
+---------+ +----------+