What is the purpose of the this keyword when used inside a constructor, and when is it necessary?
this refers to the current object.
It's necessary when a parameter has the same name as an instance variable. Without it, the assignment would just reassign the parameter to itself.
What is the output?
public class Counter {
private int count = 0;
public void increment() { count++; }
public int getCount() { return count; }
}
Counter a = new Counter();
Counter b = a;
b.increment();
System.out.println(a.getCount());
1
a and b point to the same object. Calling increment() on b modifies the single shared object, so a.getCount() also reflects the change.
What is wrong with this constructor?
public class Rectangle {
private int width, height;
public Rectangle(int width, int height) {
width = width;
height = height;
}
}
The parameters are being assigned to themselves. this.width = width and this.height = height are required. Without this, Java sees the local parameter on both sides of the =.
What is the value of Box.getCount() after this line executes?
public class Box {
private static int count = 0;
public Box() { count++; }
public static int getCount() { return count; }
}
Box[] arr = new Box[5];
System.out.println(Box.getCount());
0
Declaring an array only allocates space for 5 null references. No Box objects are actually constructed, so the constructor never runs and count is never incremented.