05 Encapsulation
05 Encapsulation
Package
package <your.package.name>;
public class <ClassName> { …}
Two rules:
A package declaration must always come first in your .java file
Naming convention: all lower case, with ‘.’ separating nested
package names, biggest package first.
Example:
package cis1068.au10.graphics;
public class Point3D { … }
Using packaged classes
4
Encapsulation
encapsulation: Hiding the implementation details of an
object from the clients of the object.
? ??
? 5
Implementing encapsulation
Examples:
private int x;
private String name;
6
Access Specifiers
8
Accessors
Example:
public int getX() {
return x;
}
9
Mutators
Example:
public void setX(int newX) {
x = newX;
}
10
Mutable and Immutable objects
13
Point class constructor
What happens if the constructor has the following
header?
public Point3D(int x, int y, int z)
14
Variable shadowing
To refer to a method:
this.<method name>(<parameters>);
16
It's like this and like that and like this and...
17
Wrapper
Classes
Wrapper classes
int x = 17;
Integer wrapX = new Integer(x);
Integer wrapX2 = x; // shorthand
// swap a with b
swap(a, b);
vs.
22