Object Oriented Programming (Encapsulation) - spc-computer-society/spc-cs-db GitHub Wiki
9. Encapsulation
Encapsulation is, essentially, data hiding. It prevents others which have this object from accessing internal data you might want to hide. You might think that this is an extra layer of complexity that we don't actually need, but encapsulation provides you, the developer, greater flexibility to change your class and how it interfaces with other code.
First, encapsulation is often provided by several access modifiers such as public, private and possibly protected. public properties can be accessed by outside code directly and often can be modified. This may make your object invalid if something which you assume is within a range may be changed. public methods can also be used directly. It is generally preferable to expose more public methods to change properties as you can do input checks before modifying values. private methods and properties can only be used within the class and cannot be accessed from outside code. protected, if it is present, allows subclass to see and use the declared methods and properties.
Consider the following:
public class Point{
private int x;
private int y;
public Point(int x,int y){
this.x = x;
this.y = y;
}
public double dist(Point other){
return Math.sqrt(Math.pow((other.x - x),2) + Math.pow(other.y - y),2));
}
}