This document discusses encapsulation in object-oriented programming. It explains that encapsulation hides implementation details and focuses on essential properties. It demonstrates encapsulation by making data fields private and providing public accessor and mutator methods. Accessors allow external code to retrieve private fields, while mutators allow changing the fields. The document provides an example Point class that encapsulates x and y coordinates with private fields and public getX(), getY(), and setLocation() methods.
2. Encapsulation
• encapsulation is hiding or protecting the implementation details
of an object from users of the object
• this creates an abstraction which allows us to focus on essential
properties rather than inner details
2
Monday, October 14, 13
3. Private fields
• To encapsulate the fields of an object, we make them private:
public class Point {
private int x;
private int y;
}
• Only visible within the Point class, but not anywhere else
3
Monday, October 14, 13
4. Accessors
• We need a way for external code to access x and y:
// can’t access private vars
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
// Point class, with *accessors*
public class Point {
private int x;
private int y;
public int
return
}
public int
return
}
}
Monday, October 14, 13
getX() {
x;
getY() {
y;
4
5. Accessors
• Write a program called PointMain that creates a new Point at
(3, 5) and prints a description of the Point
public class Point {
private int x;
private int y;
public Point(int x, int y) {
self.x = x;
self.y = y;
}
public int
return
}
public int
return
}
}
Monday, October 14, 13
getX() {
x;
getY() {
y;
5
6. Accessors
public class PointMain {
public static void main(String[] args) {
Point p = new Point(3, 5);
System.out.println("p is (" + p.getX() + ", " + p.getY() + ")");
}
}
6
Monday, October 14, 13
7. Mutators
• Write a method for Point called setLocation that takes two
integers and sets the x and y coordinates of the Point
public class Point {
private int x;
private int y;
public Point(int x, int y) {
self.x = x;
self.y = y;
}
public int
return
}
public int
return
}
}
Monday, October 14, 13
getX() {
x;
getY() {
y;
7
8. Mutators
public class Point {
private int x;
private int y;
public Point(int x, int y) {
self.x = x;
self.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
}
Monday, October 14, 13
8