This lesson introduces us to both a big new idea, and a new programming pattern. We'll show how Java enables encapsulation (big new idea) through visibility modifiers and setters and getters (new programming pattern). This is cool stuff, and allows us to achieve a much more modern and idiomatic way of creating Java classes.
So let's get started!
The new idea that we're introducing in this lesson is encapsulation. Wikipedia defines it:
In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called "getters" and "setters") to access the values, and other client classes call these methods to retrieve and modify the values within the object.
Let's unpack that definition together:
OK great—so we want to keep some parts of our
class private while allowing other parts to be public.
But how do we do that?
Here's an example:
Notice how we are using two new Java keywords—
private—to mark what parts of the class are public (available to everyone)
and what parts are private.
Let's talk a bit more about what that means:
Java actually has four visibility modifiers:
public: the variable or method can be accessed or called by anyone
private: the variable or method can be accessed or called only in code that is part of that
protected: this won't make sense to us yet, but we'll come back to it...
For now we'll stick to
protected a few lessons from now.
And keep in mind that if you don't mark a method or field as
protected, it ends up as package private.
(Another thing about Java that I dislike.)
private allow us to control access to variables and methods defined on our objects.
This supports a common Java programming pattern called setters and getters.
Let's see what those look like together:
From this point forward we will design our classes following this pattern. Instance variables or fields will always be marked as private and accessed through setters and getters, as appropriate. We'll expect you to follow that pattern on our homework problems.
Need more practice? Head over to the practice page.