Announcements
Reminder, there is a checklist of 61B tasks for weeks 1 to 5:
If you joined the class late, see the late start guide:
HW0A is due today (and ideally you’ve done it before today’s lecture!)
Further Notes for Webcast Viewers
Defining Classes. Lists and Maps.
3
Lecture 2
CS61B, Spring 2023 @ UC Berkeley
Josh Hug and Justin Yokota
Defining and Instantiating Classes
Lecture 2, CS61B, Spring 2023
Classes in Java
Lists, Arrays, and Maps
Summary
Dog
As we saw last time:
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.
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
Unlike python, there’s no need to import if the two files are in the same project.
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 MayaTheDog {
public static void makeNoise() {
System.out.println("aroooooooooo!");
}
}
public class YapsterTheDog {
public static void makeNoise() {
System.out.println("awawawwwawwa awawaw");
}
}
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 for the step-by-step process of constructing the Dog class.
These instances are also called ‘objects’
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.
These instances are also called ‘objects’
public class DogLauncher {
public static void main(String[] args) {
Dog hugeDog = new Dog(150);
hugeDog.size; // guaranteed to exist
hugeDog.name = "frank"; // syntax error!
}
}
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.
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:
public static void makeNoise() {
System.out.println("Bark!");
}
Static
Non-static
Dog.makeNoise();
maya = new Dog(100);
maya.makeNoise();
Invocation:
Invocation:
This method cannot access weightInPounds!
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else { System.out.println("woof!"); }
}
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. �
Much nicer than:
Math m = new Math();
x = m.round(x);
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weightInPounds > d2.weightInPounds) {
return d1;
}
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!");
}
}
}
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) and Project 0 (due next Friday), you’ll get much 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 get to 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 tonight at midnight.
Don’t forget about the week 1 to 5 checklist.
And if you just joined the class, make sure to see the late join guide: