KotlinCS 124 LogoJava

Encapsulation

class Person(private val age: Double) {
var name: String = ""
private set
get() {
return field + " " + field
}
fun updateName(setName: String) {
name = setName
}
}
val geoff = Person(42.0)
geoff.updateName("Geoff")
println(geoff.name)
println(geoff.age)

Welcome back! This lesson introduces us to both a big new idea, and a new programming pattern. We’ll show how Kotlin enables encapsulation (big new idea) through visibility modifiers and setters and getters (new programming pattern). This is cool stuff.

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:

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?

Kotlin provides multiple options. Here’s one:

class Person(private val name: String, private val age: Double)

Notice that we’ve introduced a visibility modifierprivate—to indicate that, while both the name and age should be set by the primary constructor, they are not available outside the class. Let’s talk a bit more about what that means:

class Person(private val name: String, private val age: Double)

Kotlin has two visibility modifiers. By default properties and methods are public—meaning that can be accessed by anyone. However, there are two other options:

  1. private: the property or method can be accessed or called only in code that is part of that class
  2. internal: this won’t make sense to us yet, but we’ll come back to it…

For now we’ll stick to private and, when omitted, to public. We’ll discuss internal a few lessons from now. And keep in mind that if you don’t mark a method or field as private or internal, it ends up as public. This is normally the right thing, so it’s a good default for Kotlin to provide.

Practice: Simple Object Method (Kotlin)

Created By: Geoffrey Challen
/ Version: 2021.2.0

Create a class called Simple that stores a single mutable Int variable in a property named value. Also provide a method squared which returns the stored value, squared.

Property Options
Property Options

When we declare properties in Kotlin as primary constructor parameters or within the class, Kotlin provides a reasonable set of defaults supporting common programming patterns. Here are some of our options.

First option: public, set in the primary constructor, can be read and written outside the class after creation:

class Person(var name: String)
val geoff = Person("Geoff")
println(geoff.name)
geoff.name = "Geoffrey"
println(geoff.name)

Note that we can use val here if we want a variable that is only set in the primary constructor and can’t change afterward.

Second option: public, not set in the primary constructor, can be read and written outside the class after creation:

class Person {
var name: String = ""
}
val geoff = Person()
println(geoff.name)
geoff.name = "Geoffrey"
println(geoff.name)

Third option: private, set in the primary constructor, can only be read and written by instance methods after creation:

class Person(private var name: String) {
fun printName() {
println(name)
}
}
val geoff = Person("Geoff")
geoff.name = "Geoffrey" // doesn't work
geoff.println(name) // instance methods can access name

Fourth option: private, not set in the primary constructor, can only be read and written by instance methods after creation:

class Person {
private var name: String = ""
fun changeName(setName: String) {
name = setName
}
fun printName() {
println(name)
}
}
val geoff = Person()
geoff.name = "Geoffrey" // doesn't work
geoff.changeName("Geoffrey") // instance methods can access name
geoff.printName()

Let’s review these options together!

class Person(var name: String)
val geoff = Person("Geoff")
println(geoff.name)
geoff.name = "Geoffrey"
println(geoff.name)

Getters and Setters
Getters and Setters

However, there are times where we need a bit more control. Let’s see how to accomplish that by customizing the methods that Kotlin uses to change variable values.

class Person(var age: Double)

If these options seem confusing, don’t worry: we’ll get lots of practice at choosing the right approach for each situation that we encounter!

Practice: Course Getters and Setters

Created By: Geoffrey Challen
/ Version: 2020.9.0

Create a public class named Course. Course should store two pieces of data: a name (as a String?) using the property name and an enrollment (as an Int) using the property enrollment. Provide a constructor that allows both properties to be set, with the name first. The name property should be publicly readable but not publicly writable, while enrollment should be both publicly readable and writable. Finally, reject negative enrollment values and null names.

Practice: Simple Object Method 2 (Kotlin)

Created By: Geoffrey Challen
/ Version: 2021.9.0

Create a class called Simple that stores a single mutable Int value in a property named value. Also provide a method inverse which returns the stored value multiplied by -1.

Homework: Simple Object Method 3 (Kotlin)

Created By: Geoffrey Challen
/ Version: 2022.9.0

Create a class called Simple that stores a single mutable Double value in a property named value. Also provide a method squared which returns the stored value squared.

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.