Announcements
I’ve created a checklist of 61B tasks for weeks 1 to 5:
If you joined the class late, please see:
HW0A is due today.
Further Notes for Webcast Viewers
Defining Classes. Lists and Maps.
3
Lecture 2
CS61B, Spring 2025 @ UC Berkeley
Josh Hug and Justin Yokota
Defining and Instantiating Classes
Lecture 2, CS61B, Spring 2025
Classes in Java
Lists, Arrays, and Maps
Summary
Coding Demo: Dog class
Dog.java
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
Error: Main method not found in class Dog
Coding Demo: Dog class
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
public static void main(String[] args) {
makeNoise();
}
}
Dog.java
Bark!
Coding Demo: Dog class
Dog.java
public class DogLauncher {
}
DogLauncher.java
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
public static void main(String[] args) {
makeNoise();
}
}
Bark!
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
DogLauncher.java
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
Bark!
Dog
As we saw last time:
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
Can’t be run directly, since there is no main method.
Calls a method from another class. Can think of this as a class that tests out the Dog class.
Unlike python, there’s no need to import if the two files are in the same project.
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
Object Instantiation
Not all dogs are equal!
A Not So Good Approach
We could create a separate class for every single dog out there, but this is going to get redundant in a hurry.
public class YapsterTheDog {
public static void makeNoise() {
System.out.println("awawawwwawwa awawaw");
}
}
public class MayaTheDog {
public static void makeNoise() {
System.out.println("aroooooooooo!");
}
}
Object Instantiation
Classes can contain not just functions (a.k.a. methods), but also data.
Classes can be instantiated as objects.
Let’s try this out. See the webcast video or the following hidden slides for the step-by-step process of constructing the Dog class.
These instances are also called ‘objects’
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
DogLauncher.java
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public static void makeNoise() {
System.out.println("Bark!");
}
}
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public static void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
} else if (weightInPounds < 30) {
System.out.println("bark.");
} else {
System.out.println("woooooof!");
}
}
}
Error: Non-static variable weightInPounds cannot be referenced from a static context.
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
} else if (weightInPounds < 30) {
System.out.println("bark.");
} else {
System.out.println("woooooof!");
}
}
}
Error: Non-static method makeNoise cannot be referenced from a static context.
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog();
d.weightInPounds = 25;
d.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
} else if (weightInPounds < 30) {
System.out.println("bark.");
} else {
System.out.println("woooooof!");
}
}
}
bark.
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog();
d.weightInPounds = 51;
d.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
} else if (weightInPounds < 30) {
System.out.println("bark.");
} else {
System.out.println("woooooof!");
}
}
}
woooooof!
Coding Demo: Dog class
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(51);
d.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weightInPounds;
public Dog(int w) {
weightInPounds = w;
}
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
} else if (weightInPounds < 30) {
System.out.println("bark.");
} else {
System.out.println("woooooof!");
}
}
}
woooooof!
Our Dog Class
public class Dog {
public int weightInPounds;
public Dog(int startingWeight) {
weightInPounds = startingWeight;
}
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
Java vs. Python Classes
public class Dog {
public int weightInPounds;
public Dog(int startingWeight) {
weightInPounds = startingWeight;
}
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
class Dog():
def __init__(self, startingWeight):
self.weightInPounds = startingWeight
def makeNoise(self):
if self.weightInPounds < 10:
print "yipyipyip!"
elif self.weightInPounds < 30:
print "bark. Bark."
else:
print "woof!"
For those of you who know Python, the equivalent code is given below.
Class Terminology
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Defining a Typical Class (Terminology)
public class Dog {
public int weightInPounds;
public Dog(int startingWeight) {
weightInPounds = startingWeight;
}
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
Constructor (similar to a method, but not a method). Determines how to instantiate the class.
Instance variable. Can have as many of these as you want.
Non-static method, a.k.a. Instance Method. Idea: If the method is going to be invoked by an instance of the class (as in the next slide), then it should be non-static.
Roughly speaking: If the method needs to use “my instance variables”, the method must be non-static.
Object Instantiation
Classes can contain not just functions (a.k.a. methods), but also data.
Classes can be instantiated as objects.
public class DogLauncher {
public static void main(String[] args) {
Dog hugeDog = new Dog(150);
hugeDog.weightInPounds = 5; // guaranteed to exist
hugeDog.name = "frank"; // syntax error!
}
}
These instances are also called ‘objects’
Instantiating a Class and Terminology
public class DogLauncher {
public static void main(String[] args) {
Dog smallDog;
new Dog(20);
smallDog = new Dog(5);
Dog hugeDog = new Dog(150);
smallDog.makeNoise();
hugeDog.makeNoise();
}
}
Declaration of a Dog variable.
Instantiation of the Dog class as a Dog Object.
Instantiation and Assignment.
Declaration, Instantiation and Assignment.
Invocation of the 150 lb Dog’s makeNoise method.
The dot notation means that we want to use a method or variable belonging to hugeDog, or more succinctly, a member of hugeDog.
Arrays of Objects
To create an array of objects:
Example:�
After code runs:
Dog[] dogs = new Dog[2];
dogs[0] = new Dog(8);
dogs[1] = new Dog(20);
dogs[0].makeNoise();
Dog of size 8 | Dog of size 20 |
0
1
dogs =
Yipping occurs.
Creates an array of Dogs of size 2.
Static vs. Instance Members
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Static vs. Non-Static
Key differences between static and non-static (a.k.a. instance) methods:
Dog maya = new Dog(100);
maya.makeNoise();
Dog.makeNoise();
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else { System.out.println("woof!"); }
}
public static void makeNoise() {
System.out.println("Bark!");
}
Static
Non-static
Invocation:
Invocation:
This method cannot access weightInPounds!
Why Static Methods?
Some classes are never instantiated. For example, Math.
Sometimes, classes may have a mix of static and non-static methods, e.g.
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weightInPounds > d2.weightInPounds) {
return d1;
}
return d2;
}
Much nicer than:
Math m = new Math();
x = m.round(x);
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
d.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
}
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
Dog d2 = new Dog(100);
Dog bigger = Dog.maxDog(d, d2);
bigger.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
}
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
Dog d2 = new Dog(100);
Dog bigger = Dog.maxDog(d, d2);
bigger.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weight > d2.weight) {
return d1;
}
return d2;
}
}
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
Dog d2 = new Dog(100);
Dog bigger = Dog.maxDog(d, d2);
bigger.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weight > d2.weight) {
return d1;
}
return d2;
}
public Dog maxDog(Dog d2) {
if (weight > d2.weight) {
return this;
}
return d2;
}
}
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
Dog d2 = new Dog(100);
Dog bigger = Dog.maxDog(d, d2);
bigger.makeNoise();
bigger = d.maxDog(d2);
bigger.makeNoise();
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weight > d2.weight) {
return d1;
}
return d2;
}
public Dog maxDog(Dog d2) {
if (weight > d2.weight) {
return this;
}
return d2;
}
}
Coding Demo: maxDog
Dog.java
public class DogLauncher {
public static void main(String[] args) {
Dog d = new Dog(15);
Dog d2 = new Dog(100);
Dog bigger = Dog.maxDog(d, d2);
bigger.makeNoise();
bigger = d.maxDog(d2);
bigger.makeNoise();
System.out.println(Dog.binomen);
}
}
DogLauncher.java
public class Dog {
int weight;
public Dog(int w) { ... }
public void makeNoise() { ... }
public static String binomen = "canis";
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weight > d2.weight) {
return d1;
}
return d2;
}
public Dog maxDog(Dog d2) {
if (weight > d2.weight) {
return this;
}
return d2;
}
}
Static Variables (are Dangerous)
Classes can also have static variables.
public class Dog {
public int weightInPounds;
public static String binomen = "Canis familiaris";
public Dog(int startingWeight) {
weightInPounds = startingWeight;
}
...
}
Never changes. It’s a constant.
Static vs. Non-Static
A class may have a mix of static and non-static members.
public class Dog {
public int weightInPounds;
public static String binomen = "Canis familiaris";
public Dog(int startingWeight) {
weightInPounds = startingWeight;
}
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weightInPounds > d2.weightInPounds)
{ return d1; }
return d2;
}
...
...
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
Puzzle: Will this program compile? If so, what will it print?
public class DogLoop {
public static void main(String[] args) {
Dog smallDog = new Dog(5);
Dog mediumDog = new Dog(25);
Dog hugeDog = new Dog(150);
Dog[] manyDogs = new Dog[4];
manyDogs[0] = smallDog;
manyDogs[1] = hugeDog;
manyDogs[2] = new Dog(130);
int i = 0;
while (i < manyDogs.length) {
Dog.maxDog(manyDogs[i], mediumDog).makeNoise();
i = i + 1;
}
}
}
< 10: yip
< 30: bark
>=30: woof
Answer to Question
Won’t go over in live lecture.
Use the Java visualizer to see the solution here: http://goo.gl/HLzN6s
Video solution: https://www.youtube.com/watch?v=Osuy8UEH03M
Lists in Java 4.0
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Lists
In programming languages, a list is an ordered sequence of objects, often represented by comma-separated values in-between brackets.
Example: [3, 6, 9, 12, 15]
Lists support a variety of operations which vary according to the whims of the authors who wrote the code for the list. Some examples:
For more, see wikipedia: https://en.wikipedia.org/wiki/List_(abstract_data_type)
Lists in Python
Python lists have very simple syntax, given below.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
Lists in Java
Let’s try to make a copy of the code below using IntelliJ.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
Lists in Java Attempt #1
Let’s try to make a copy of the code below using IntelliJ.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
public class ListDemo {
public static void main(String[] args) {
List L = new List();
}
}
Can either add import statement to code, or use the IntelliJ option-enter or alt-enter hotkey.
Lists in Java Attempt #2
Let’s try to make a copy of the code below using IntelliJ.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List L = new List();
}
}
Lists in Java Attempt #3
This code finally compiles.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List L = new ArrayList();
}
}
We’ll talk about this distinction shortly.
Lists in Java Attempt #3
We’ve written the equivalent Java program!
Now let’s reflect on that distinction between List and ArrayList.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List L = new ArrayList();
L.add("a");
L.add("b");
L.add("c");
System.out.println(L);
}
}
Abstract Data Types vs. Concrete Implementations
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Alternate Types of List
Java has other types of Lists. Let’s take a peek:
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List x = new ArrayList();
...
}
}
Alternate Types of List
Java has other types of Lists. Let’s take a peek:
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List x = new LinkedList();
...
}
}
List
In Python, there is no distinction between the abstract idea of a list and an actual list.
In Java, there are many types of lists.
L = []
L.append("a")
L.append("b")
L.append("c")
print(L)
['a', 'b', 'c']
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List x = new LinkedList();
...
}
}
Abstract Data Types vs. Concrete Implementations
Another term used for List in Java is “Abstract Data Type”.
Each implementation, e.g. LinkedList, is known as a “Concrete Implementation”.
List
ArrayList
Linked
List
CopyOnWriteArrayList
...
...
Abstract Data Types
Why bother having multiple implementations? What do you think?
List
ArrayList
Linked
List
CopyOnWriteArrayList
...
...
Abstract Data Types
Why bother having multiple concrete implementations of an abstract data type?
We’ll come to explore this concept in much more detail next week. For now, let’s get back to modernizing our Java code.
List
ArrayList
Linked
List
CopyOnWriteArrayList
...
...
Modern Java Lists
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Retrieving from Lists
In Python, we retrieve items by using bracket notation.
L = []
L.append("a")
L.append("b")
print(L[0])
a
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List L = new ArrayList();
L.add("a");
L.add("b");
}
}
Retrieving from Lists
In Java, we retrieve items using .get.
L = []
L.append("a")
L.append("b")
print(L[0])
a
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List L = new ArrayList();
L.add("a");
L.add("b");
System.out.println(L.get(0));
}
}
Java 4.0 List Limitation
The list we created is a Java 4.0 style list (from Java before 2005).
L = []
L.append("a")
L.append("b")
x = L[0]
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List L = new ArrayList();
L.add("a");
L.add("b");
String x = L.get(0);
}
}
Won’t compile. Results in a “Required type: String, Provided: Object” error.
Java 5.0 Lists
In 2005, a new angle bracket syntax was introduced to deal with this issue.
L = []
L.append("a")
L.append("b")
x = L[0]
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List<String> L = new ArrayList<>();
L.add("a");
L.add("b");
String x = L.get(0);
}
}
Historical note: You had to have <String> on both declaration and instantiation sides until 2011.
Java 5.0 Lists
All items in a list created using bracket notation must have the same type!
L = []
L.append("a")
L.append(3)
# fine
import java.util.List;
import java.util.ArrayList;
public class ListDemo {
public static void main(String[] args) {
List<String> L = new ArrayList<>();
L.add("a");
L.add(3);
}
}
Syntax error. Won’t compile.
Limitations
Going from Java 4.0 to Java 5.0 lists meant losing the ability to have lists with multiple types.
Why might this be a good thing?
Limitations (My Answer)
Going from Java 4.0 to Java 5.0 lists meant losing the ability to have lists with multiple types.
Why might this be a good thing?
Placing limitations on yourself as a programmer is a good thing!
Arrays
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Arrays
Java has a special collection called an “array” that is a restricted version of the list ADT.
No python equivalent.
public class ArrayDemo {
public static void main(String[] args) {
String[] x = new String[5]; // size 5
x[0] = "a";
x[1] = "b";
System.out.println(x[0]);
}
}
Question for You
Why do you think Java has both lists and arrays (basically lists with fewer features)?
Question for You (My Answers)
Why do you think Java has both lists and arrays?
Question for You
Why do you think Java favors arrays over lists (has special bracket syntax, doesn’t require imports)?
Question for You (My Answer)
Why do you think Java favors arrays over lists (has special bracket syntax, doesn’t require imports)?
Side note, when you take 61C, you’ll learn C.
Maps
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Maps
In programming languages, a map is collection of key-value pairs. Each key is guaranteed to be unique. Also called:
Example: {“alpha”: “first letter of greek alphabet”,
“potato”: “a starchy edible plant”}
For more, see: https://en.wikipedia.org/wiki/Associative_array
Maps in Python
Below, we see a simple example where we create a dictionary (a.k.a. map) in Python.
m = {}
m["cat"] = "meow"
m["dog"] = "woof"
sound = m["cat"]
Maps in Python
On HW0B (due Monday) you’ll get more practice with maps.
m = {}
m["cat"] = "meow"
m["dog"] = "woof"
sound = m["cat"]
import java.util.Map;
import java.util.TreeMap;
public class MapDemo {
public static void main(String[] args) {
Map<String, String> L = new TreeMap<>();
L.put("dog", "woof");
L.put("cat", "meow");
String sound = L.get("cat");
}
}
Summary
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Most Common List and Map Implementations
The most common Map implementations are TreeMap and HashMap.
Starting next week, we’ll be digging into the distinction between LinkedLists and ArrayLists.
Will more fully discuss TreeMaps and HashMaps in roughly week 7 of the course.
List
ArrayList
Linked
List
Map
HashMap
TreeMap
Todo!
Now it’s time to get started on HW0B.
Project 0 will be released by tomorrow evening.
Don’t forget about the week 1 to 5 checklist.
And if you just joined the class, make sure to see https://sp25.datastructur.es/policies/#late-adding-cs61b