1 of 49

Defining and Using Classes

1

Lecture 2

CS61B, Fall 2024 @ UC Berkeley

Slides credit: Josh Hug

2 of 49

Defining and Instantiating Classes

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

3 of 49

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

4 of 49

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!

5 of 49

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!

6 of 49

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!

7 of 49

Dog

As we saw last time:

  • Every method (a.k.a. function) is associated with some class.
  • To run a class, we must define a main method.
    • Not all classes have a main method!

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!");

}

}

8 of 49

Object Instantiation

Not all dogs are equal!

9 of 49

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!");

}

}

10 of 49

Object Instantiation

Classes can contain not just functions (a.k.a. methods), but also data.

  • For example, we might add a size variable to each Dog.

Classes can be instantiated as objects.

  • We’ll create a single Dog class, and then create instances of this Dog.
  • The class provides a blueprint that all Dog objects will follow.
    • For the example above, all Dog objects will have a size.

Let’s try this out.

These instances are also called ‘objects’

11 of 49

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!");

}

}

12 of 49

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!");

}

}

13 of 49

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.

14 of 49

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.

15 of 49

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.

16 of 49

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!

17 of 49

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!

18 of 49

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!");

}

}

}

19 of 49

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.

20 of 49

Class Terminology

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

21 of 49

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.

22 of 49

Object Instantiation

Classes can contain not just functions (a.k.a. methods), but also data.

  • For example, we might add a size variable to each Dog.

Classes can be instantiated as objects.

  • We’ll create a single Dog class, and then create instances of this Dog.
  • The class provides a blueprint that all Dog objects will follow.
    • For the example above, all Dog objects will have a size.
    • Cannot add new instance variables to a Dog. They must ALL obey the blueprint exactly.

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’

23 of 49

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.

24 of 49

Arrays of Objects

To create an array of objects:

  • First use the new keyword to create the array.
  • Then use new again for each object that you want to put in the array.

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.

25 of 49

Static vs. Instance Members

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

26 of 49

Static vs. Non-Static

Key differences between static and non-static (a.k.a. instance) methods:

  • Static methods are invoked using the class name, e.g. Dog.makeNoise();
  • Instance methods are invoked using an instance name, e.g. maya.makeNoise();
  • Static methods can’t access “my” instance variables, because there is no “me”.

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!

27 of 49

Why Static Methods?

Some classes are never instantiated. For example, Math.

  • x = Math.round(5.6);

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);

28 of 49

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() { ... }

}

29 of 49

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() { ... }

}

30 of 49

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;

}

}

31 of 49

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;

}

}

32 of 49

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;

}

}

33 of 49

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;

}

}

34 of 49

Static Variables (are Dangerous)

Classes can also have static variables.

  • You should always access class variables using the class name, not an instance name.
    • Bad coding style to do something like maya.binomen.
    • Even worse to do something like maya.binomen = “Vulpes vulpes”
  • Warning: Strongly recommended to avoid static variables whose values change.
    • Leads to complicated code: Becomes hard to mentally keep track of which parts of your program read and write from/to the static variable. For more read this.

public class Dog {

public int weightInPounds;

public static String binomen = "Canis familiaris";

public Dog(int startingWeight) {

weightInPounds = startingWeight;

}

...

}

Never changes. It’s a constant.

35 of 49

Static vs. Non-Static

A class may have a mix of static and non-static members.

  • A variable or method defined in a class is also called a member of that class.
  • Static members are accessed using class name, e.g. Dog.binomen.
  • Non-static members cannot be invoked using class name: Dog.makeNoise()
  • Static methods must access instance variables via a specific instance, e.g. d1.

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!");

}

}

}

36 of 49

Practice Question

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

37 of 49

Question: 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

38 of 49

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

39 of 49

Interactive Debugging

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

40 of 49

Interactive Debugging

So far (e.g. in CS61A), you might have added print statements to find bugs in your code.

Today, we'll use IntelliJ's built-in, interactive debugging tool to find bugs in some code.

41 of 49

Goal: Larger Than Four Neighbors

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

42 of 49

Goal: largerThanFourNeighbors

Suppose we want to write a method:

This method will return a new array that contains every Dog that is larger than its 4 closest neighbors, i.e. the two on the left and the two in the right.

If there are not enough neighbors, i.e. you’re at the end of the array, then consider just the neighbors that exist.

For example:

  • Input: Dogs with size [10, 20, 30, 25, 20, 40, 10]
  • Returns: Dogs with size [30, 40].
    • 30 is greater than 10, 20, 25, and 20.
    • 40 is greater than 25, 20, and 10.

public static Dog[] largerThanFourNeighbors(Dog[] dogs)

43 of 49

Goal: largerThanFourNeighbors

Suppose we want to write a method:

If input Dog sizes are [10, 15, 20, 15, 10, 5, 10, 15, 22, 20], what will be the size of the Dogs returned?

  1. [20]
  2. [20, 22]
  3. [20, 22, 20]

public static Dog[] largerThanFourNeighbors(Dog[] dogs)

44 of 49

Goal: largerThanFourNeighbors

Suppose we want to write a method:

If input Dog sizes are [10, 15, 20, 15, 10, 5, 10, 15, 22, 20], what will be the size of the Dogs returned?

  • [20]
  • [20, 22]
  • [20, 22, 20]

public static Dog[] largerThanFourNeighbors(Dog[] dogs)

45 of 49

Using the Debugger

Lecture 2, CS61B, Fall 2024

Classes in Java

  • Defining and Instantiating Classes
  • Class Terminology
  • Static vs. Instance Members
  • Practice Question

Interactive Debugging

  • Goal: Larger Than Four Neighbors
  • Using the Debugger

46 of 49

Setting Breakpoints

  • Breakpoints: Places in the code where the debugger will pause and let you inspect the program state.
  • In IntelliJ:
    • To set/unset breakpoints, click just to the right of the line number.
    • Breakpoints are highlighted in red.
    • Click to launch the debugger and run the program, pausing at breakpoints.

47 of 49

Inspecting Program State

  • When the program is paused, you can view the values of all the variables (as if you had added print statements).
  • You can also execute lines of code interactively in the "Evaluate expression" box.

public static int addOne(int x) {

int retValue = x + 1;

return retValue;

}

public static void main(String[] args) {

int y = addOne(5);

System.out.println(y);

}

48 of 49

Stepping Over vs. Stepping In

  • IntelliJ highlights the line about to execute (has not executed yet).
  • If the highlighted line contains a function call:
    • steps over the function call, and pauses at the next line after calling the function.�Useful if you don't care about the code inside the function.
    • steps into the function call, and pauses at the first line of the function.�Useful if you want to step through the code inside the function.

public static int addOne(int x) {

int retValue = x + 1;

return retValue;

}

public static void main(String[] args) {

int y = addOne(5);

System.out.println(y);

}

Step over pauses the program here

Step into pauses the program here

49 of 49

Continue

  • You can set multiple breakpoints.
  • resumes running the program, pausing at the next breakpoint encountered.

public static Dog[] largerThanFourNeighbors(Dog[] dogs) {

Dog[] returnDogs = new Dog[dogs.length];

int cnt = 0;

for (int i = 0; i < dogs.length; i += 1) {

if (isBiggestOfFour(dogs, i)) {

returnDogs[cnt] = dogs[i];

cnt = cnt + 1;

}

}

returnDogs = arrayWithNoNulls(returnDogs, cnt);

return returnDogs;

}

If we're currently paused here...

will run the entire for loop, and pause the program at this breakpoint