Accessors and Mutators
Accessor Methods
- Get a variable from an Object
// main class
Point pt1 = new Point();
double x1 = pt1.getX();
|
<-
|
// Point
double x = 20.0;
double getX () {
return x;
}
|
Mutator Methods
- Set a variable in an object
// main class
Point p1 = new Point();
p1.setX(222.2);
|
->
|
// Point
double x = 0.0;
void setX (double xIn) {
x = xIn;
}
|
Together
public class Point {
double x = 0.0;
void setX (double xIn) {
x = xIn;
}
double getX() {
return x;
}
}
Scope
public class Point {
double x = 0.0; <-- Instance variable
void setX (double xIn) { <-- Parameter variable
x = xIn;
}
double getX() {
return x;
}
void someMethod () {
double a = 10.0; <-- Method variable
}
}
this
keyword
- What if you use the same name?
public class Point{
double x = 200.0;
void setX (double x) {
this.x = x;
}
}
Access
- It's fine for encapsulation to demand accessors and mutators, but how do we enforce it?
- Access modifier keywords:
public
: usable by anyone;
protected
: usable by classes that inherit;
private
: only useable by the object.
- Default is code can be seen only in same directory (package - which we'll come back to).
Variable access
public class Point {
private double x = 0.0;
public void setX (double xIn) {
x = xIn;
}
public double getX() {
return x;
}
}
Variable access
- If variables are declare
final
they can't be altered.
- Such variables are known as 'constants' in other languages.
- Conventionally in uppercase and underscores, e.g.:
// 10 year dollar average per kilo
final int PRICE_OF_GOLD = 10100;
final int PRICE_OF_SILVER = 202;
final int PRICE_OF_BEER = 4;
Review
- Get used to assuming any variable you want another class to interact with has 'set' and 'get' mutator and accessor methods.
- Always make these public (or protected) and the variables private.