31. Capsulate Fields public class Point { private int xCoord; private int yCoord; // constructing code ... public int getXCoord() { return this.xCoord; } public void setXCoord(int value) { this.xCoord = value; } public int get Y Coord() { return this. y Coord; } public void set Y Coord(int value) { this. y Coord = value; } // More code ... } Fields are encapsulated as private members Getters and Setter allow controlled access to the private fields
38. Static Members – Example public class Sequence { private static int currentValue = 0; private Sequence() { // Deny instantiation of this class } public static int nextValue() { currentValue++; return currentValue; } } public class TestSequence { public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ", Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue()); } }
40. Creating Static Methods public class Fraction { private int numerator; private int denominator; public Fraction(int num, int denom) { this.numerator = num; this.denominator = denom; } public static Fraction Parse( S tring val) { S tring[] parts = val. s plit( " / " ); int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom); return result; } }