0% found this document useful (0 votes)
19 views32 pages

(61B FA24) Lecture 2 - Defining and Using Classes

Lecture 2 of CS61B at UC Berkeley focuses on defining and using classes in Java, covering topics such as class instantiation, terminology, and the differences between static and instance members. It includes practical examples with a Dog class, methods for object instantiation, and interactive debugging techniques using IntelliJ. The lecture also poses questions about class functionality and introduces the concept of debugging through breakpoints and inspecting program state.

Uploaded by

sunxiaolong0728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views32 pages

(61B FA24) Lecture 2 - Defining and Using Classes

Lecture 2 of CS61B at UC Berkeley focuses on defining and using classes in Java, covering topics such as class instantiation, terminology, and the differences between static and instance members. It includes practical examples with a Dog class, methods for object instantiation, and interactive debugging techniques using IntelliJ. The lecture also poses questions about class functionality and introduces the concept of debugging through breakpoints and inspecting program state.

Uploaded by

sunxiaolong0728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Lecture 2

Defining and Using Classes


CS61B, Fall 2024 @ UC Berkeley
Slides credit: Josh Hug

1
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
Defining and • Practice Question
Interactive Debugging
Instantiating • Goal: Larger Than Four
Neighbors
Classes • Using the Debugger

Lecture 2, CS61B, Fall 2024


Dog
As we saw last time: Unlike python,
● Every method (a.k.a. function) is associated with some class. there’s no need
● To run a class, we must define a main method. to import if the
two files are in
○ Not all classes have a main method! the same
project.
public class Dog {
public static void
makeNoise() { Can’t be run directly,
since there is no main
method.
System.out.println("Bark!");
}
}
public class DogLauncher {
public static void main(String[] Calls a method from
another class. Can think
args) { of this as a class that
Dog.makeNoise(); tests out the Dog class.
}
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.
● For example, we might add a size variable to each Dog.
These instances are
also called ‘objects’
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.


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 { For those of you who know Python, the
public int weightInPounds; equivalent code is given below.

public Dog(int startingWeight) {


weightInPounds = startingWeight;
}

public void makeNoise() {


if (weightInPounds < 10) { class Dog():
System.out.println("yipyipyip!"); def __init__(self, startingWeight):
} else if (weightInPounds < 30) { self.weightInPounds =
startingWeight
System.out.println("bark. bark.");
} else {
System.out.println("woof!"); def makeNoise(self):
} if self.weightInPounds < 10:
} print "yipyipyip!"
} elif self.weightInPounds < 30:
print "bark. Bark."
else:
print "woof!"
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
• Practice Question
Interactive Debugging
Class • Goal: Larger Than Four
Neighbors
Terminology • Using the Debugger

Lecture 2, CS61B, Fall 2024


Defining a Typical Class (Terminology)

public class Dog {


public int weightInPounds; Instance variable. Can have as
many of these as you want.
public Dog(int startingWeight) { Constructor (similar to a method,
weightInPounds = startingWeight; but not a method). Determines how
to instantiate the class.
}

public void makeNoise() { Non-static method, a.k.a.


Instance Method. Idea: If the
if (weightInPounds < 10) { method is going to be invoked by
System.out.println("yipyipyip!"); an instance of the class (as in the
} else if (weightInPounds < 30) { next slide), then it should be non-
System.out.println("bark. static.
bark.");
Roughly speaking: If the method
} else { needs to use “my instance
System.out.println("woof!"); variables”, the method must be
} non-static.
}
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.
These instances
Classes can be instantiated as objects. are also called
‘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!
}
Instantiating a Class and Terminology

public class DogLauncher {


public static void main(String[]
args) { Declaration of a Dog variable.
Instantiation of the Dog class as a Dog
Dog smallDog; Object.
new Dog(20); Instantiation and Assignment.
Declaration, Instantiation and
smallDog = new Dog(5); Assignment.
Dog hugeDog = new Dog(150);
Invocation of the 150 lb Dog’s makeNoise
smallDog.makeNoise(); method.
hugeDog.makeNoise();
}
}
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:
● 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:

Dog[] dogs = new Dog[2]; Creates an array of Dogs of size 2.


dogs[0] = new Dog(8);
dogs[1] = new Dog(20);
dogs[0].makeNoise(); Yipping occurs.

After code runs:

dogs = Dog of size 8 Dog of size 20

0 1
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
Static vs. • Practice Question
Interactive Debugging
Instance • Goal: Larger Than Four
Neighbors
Members • Using the Debugger

Lecture 2, CS61B, Fall 2024


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”. Non-static

Static public void makeNoise() {


if (weightInPounds < 10) {
public static void makeNoise() System.out.println("yipyipyip!");
{ } else if (weightInPounds < 30) {
System.out.println("bark. bark.");
System.out.println("Bark!"); } else { System.out.println("woof!");
} }
This method cannot access }
weightInPounds!
Dog maya = new
Invocation: Dog.makeNoise() Invocation:
Dog(100);
;
maya.makeNoise();
Why Static Methods?
Some classes are never instantiated. For example, Math.
● x = Math.round(5.6);
Much nicer than:

Math m = new Math();


x = m.round(x);
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;
}
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
public which
classparts
Dog of{ your program read and write from/to the static variable.
For more
public read this.
int weightInPounds; Never
public static String binomen = "Canis changes. It’s
familiaris"; a constant.

public Dog(int startingWeight) {


weightInPounds = startingWeight;
}
...
}
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) { public void makeNoise() {
weightInPounds = startingWeight; if (weightInPounds < 10) {
}
System.out.println("yipyipyip!");
public static Dog maxDog(Dog d1, Dog d2) { } else if (weightInPounds < 30) {
if (d1.weightInPounds > d2.weightInPounds) System.out.println("bark.
{ return d1; } bark.");
return d2; } else {
} System.out.println("woof!");
... }
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
• Practice Question
Interactive Debugging
Practice • Goal: Larger Than Four
Neighbors
Question • Using the Debugger

Lecture 2, CS61B, Fall 2024


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); < 10: yip
Dog mediumDog = new Dog(25);
Dog hugeDog = new Dog(150); < 30:
bark
Dog[] manyDogs = new Dog[4];
manyDogs[0] = smallDog; >=30:
manyDogs[1] = hugeDog;
woof
manyDogs[2] = new Dog(130);

int i = 0;
while (i < manyDogs.length) {
Dog.maxDog(manyDogs[i],
mediumDog).makeNoise();
i = i + 1;
}
}
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
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
• Practice Question
Interactive Debugging
Interactive • Goal: Larger Than Four
Neighbors
Debugging • Using the Debugger

Lecture 2, CS61B, Fall 2024


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.
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
Goal: Larger • Practice Question
Interactive Debugging
Than Four • Goal: Larger Than Four
Neighbors
Neighbors • Using the Debugger

Lecture 2, CS61B, Fall 2024


Goal: largerThanFourNeighbors
Suppose we want to write a method:

public static Dog[] largerThanFourNeighbors(Dog[]


dogs)
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.
Goal: largerThanFourNeighbors
Suppose we want to write a method:

public static Dog[] largerThanFourNeighbors(Dog[]


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

A. [20]
B. [20, 22]
C. [20, 22, 20]
Goal: largerThanFourNeighbors
Suppose we want to write a method:

public static Dog[] largerThanFourNeighbors(Dog[]


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

A. [20]
B. [20, 22]
C. [20, 22, 20]
Classes in Java
• Defining and Instantiating
Classes
• Class Terminology
• Static vs. Instance Members
• Practice Question
Interactive Debugging
Using the • Goal: Larger Than Four
Neighbors
Debugger • Using the Debugger

Lecture 2, CS61B, Fall 2024


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.
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);
}
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; Step into pauses the program
return retValue; here
}

public static void main(String[]


args) {
int y = addOne(5); Step over pauses the program
System.out.println(y); here
}
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]; If we're currently paused
int cnt = 0; here...

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


if (isBiggestOfFour(dogs, i)) {
returnDogs[cnt] = dogs[i];
cnt = cnt + 1;
}
}
will run the entire
returnDogs = arrayWithNoNulls(returnDogs, cnt); for loop, and pause the
return returnDogs; program at this
} breakpoint

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy