Joseph Haugh
University of New Mexico
new to create objects, dot notation to access fields and methodsprivate fields + public methods = encapsulationclass Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public String toString() {
return "(" + x + ", " + y + ")";
}
}
this distinguishes the field from the parameter when names clashfinal keyword: locking values so they can’t be changedstatic keyword: things that belong to the class, not to any objectfinal Keywordfinal means: once set, cannot be reassignedfinal Local Variablesvoid main() {
final int MAX = 100;
IO.println(MAX); // 100
MAX = 200; // COMPILE ERROR: cannot assign a value to final variable MAX
}
final Fieldsfinalclass Circle {
private final double radius;
public Circle(double radius) {
this.radius = radius; // assigned here, and never again
}
public double area() {
return Math.PI * radius * radius;
}
}
final Fieldsvoid main() {
Circle c = new Circle(5.0);
IO.println(c.area()); // 78.53...
c.radius = 10.0; // COMPILE ERROR: radius is private AND final
}
final field communicates: this value defines the object and will never changefinal Parametersfinaldouble calculateTax(final double income) {
income = 0; // COMPILE ERROR: cannot assign a value to final variable income
return income * 0.25;
}
final Arrays: The Gotchafinal on an array means the array is completely frozenfinal only locks the variable, you cannot reassign it to a new arrayfinal Arrays: Examplevoid main() {
final int[] scores = {10, 20, 30};
// This is FINE, changing the contents
scores[0] = 99;
IO.println(scores[0]); // 99
// This is a COMPILE ERROR, reassigning the variable
scores = new int[]{1, 2, 3};
}
final Arrays: Visualizedfinal int[] scores = {10, 20, 30};
final locks the arrow, scores must always point to this arrayscores -> [ 10 | 20 | 30 ]
^
contents are NOT locked
final != immutable. If you want truly immutable data you need other tools (not covered today).final| Situation | Use final? |
|---|---|
A constant value that never changes (e.g., MAX_SIZE) |
Yes |
A field that is set once and defines the object (e.g., id) |
Yes |
| A regular variable that might change later | No |
| An array whose reference shouldn’t change | Yes, but remember contents can still change |
static KeywordPoint has its own x and yBankAccount has its own balancestatic is forclass Counter {
private static int count = 0; // shared by ALL Counter objects
private int id;
public Counter() {
count++;
this.id = count;
}
public static int getCount() { return count; }
public int getId() { return id; }
}
void main() {
Counter a = new Counter();
Counter b = new Counter();
Counter c = new Counter();
IO.println(a.getId()); // 1
IO.println(b.getId()); // 2
IO.println(c.getId()); // 3
IO.println(Counter.getCount()); // 3
}
count is one variable shared by all three objectsCounter.getCount() using the class name, not an objectthis, it cannot access instance fields or instance methodsClassName.methodName()Math.sqrt(25.0) // Math is a class; sqrt is a static method
Math.abs(-5)
Math.max(3, 7)
class MathUtils {
public static int square(int x) {
return x * x;
}
public static boolean isEven(int n) {
return n % 2 == 0;
}
}
void main() {
IO.println(MathUtils.square(5)); // 25
IO.println(MathUtils.isEven(4)); // true
IO.println(MathUtils.isEven(7)); // false
}
Instance method
class Circle {
private double r;
public Circle(double r) {
this.r = r;
}
// Needs an object,
// uses field r
public double area() {
return Math.PI * r * r;
}
}
Circle c = new Circle(5.0);
c.area(); // called on an object
Static method
class MathUtils {
// No object needed, uses only params
public static double circleArea(double r) {
return Math.PI * r * r;
}
}
// called on the class
MathUtils.circleArea(5.0);
static when the method or field does not depend on any object’s state
Math.sqrt, converters, validators)Math.PI, MAX_SIZE)static when:
thisclass Dog {
private String name;
public Dog(String name) {
this.name = name;
}
// BUG: static method trying to use an instance field
public static void bark() {
IO.println(name + " says: Woof!"); // COMPILE ERROR
}
}
static methods have no this, they can’t see namestatic, or pass name as a parameterpublic static final for class-level constantsclass Circle {
public static final double PI = 3.14159265358979;
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return PI * radius * radius;
}
}
static: one copy for the class, not per objectfinal: value can never be changedpublic: anyone can read itstatic final vs. instance finalstatic final |
instance final |
|
|---|---|---|
| How many copies? | One, shared by all objects | One per object |
| Example | Math.PI, MAX_SIZE |
a person’s unique ID |
| Accessed via | Class name | Object reference |
| Set when? | At declaration | In the constructor |
final
final array: reference is locked, contents are notstatic
this cannot access instance fieldsClassName.method() or ClassName.field