KotlinCS 124 LogoJava

Encapsulation

public class Person {
private String name;
private double age;
Person(String setName, double setAge) {
name = setName;
age = setAge;
}
public String getName() {
return name;
}
public void setName(String setName) {
name = setName;
}
public double getAge() {
return age;
}
public void setAge(double setAge) {
age = setAge;
}
}
Person person = new Person("Geoff", 41.05);
System.out.println(person.getName());
person.setName("Excellent Student");
System.out.println(person.getName());

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!

Encapsulation
Encapsulation

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:

https://www.youtube.com/watch?v=6BLUbNG4LK0

Visibility Modifiers
Visibility Modifiers

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:

public class Person {
private String name;
private double age;
public Person(String setName, double setAge) {
name = setName;
age = setAge;
}
}

Notice how we are using two new Java keywords—public and 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:

public class Person {
private String name;
private double age;
public Person(String setName, double setAge) {
name = setName;
age = setAge;
}
}

Java actually has four visibility modifiers:

  1. public: the variable or method can be accessed or called by anyone
  2. private: the variable or method can be accessed or called only in code that is part of that class
  3. protected: this won’t make sense to us yet, but we’ll come back to it…
  4. : yes, even the absence of a visibility modifier is meaningful and known as package private, but it also won’t make sense yet either

For now we’ll stick to public and private. We’ll discuss protected a few lessons from now. And keep in mind that if you don’t mark a method or field as public, private, or protected, it ends up as package private. (Another thing about Java that I dislike.)

Practice: Simple Object Method

Created By: CS 124 Staff
/ Version: 2020.9.0

Create a public class called Simple. Simple should store a single int value in a private field and provide a public setValue method that sets the stored int to the passed value. (You can initialize the stored value to 0.) It should also provide a public method called squared that takes no parameters and returns the stored value, squared. Do not implement getValue.

Setters and Getters
Setters and Getters

public and 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:

public class Person {
private String name;
private double age;
public Person(String setName, double setAge) {
name = setName;
age = setAge;
}
}

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.

Practice: Course Getters and Setters

Created By: CS 124 Staff
/ Version: 2020.9.0

Create a public class named Course. Course should store two pieces of data: a name (as a String) and an enrollment (as an int). Provide a public constructor that allows both fields to be set, with the name first. Following the encapsulation pattern we have introduced, provide both a setter and a getter for the enrollment as getEnrollment and similar. Provide only a getter for the name as getName. Finally, reject negative enrollment values and null names using assert.

Practice: Simple Object Method 2

Created By: CS 124 Staff
/ Version: 2021.9.0

Create a public class called Simple. Simple should store a single int value in a private field and provide a public setValue method that sets the stored int to the passed value. (You can initialize the stored value to 0.) It should also provide a public method called inverse that takes no parameters and returns the stored value multiplied by -1. Do not implement getValue.

Homework: Simple Object Method 3

Created By: CS 124 Staff
/ Version: 2022.9.0

Create a public class called Simple. Simple should store a single double value in a private field and provide a public setValue method that sets the stored double to the passed value. (You can initialize the stored value to 0.0.) It should also provide a public method called squared that takes no parameters and returns the stored value squared. Do not implement getValue.

CS People: Molly White
CS People: Molly White

While technology can be a force for good in the world, like anything else created by humans, its impact can easily go off in other directions. Molly White—a software engineer by trade—has established a reputation as a prominent critic of Web3 and cryptocurrencies, two technologies implicated in several recent scams and scandals. Her website, Web3 Is Going Just Great, provides a refreshing persepctive on the failures and follies in a very frothy space.

In the interview below, Molly White discusses why crypto critics matter(1):

More Practice

Need more practice? Head over to the practice page.

˝