Defining and Using Classes
1
Lecture 2
CS61B, Fall 2024 @ UC Berkeley
Slides credit: Josh Hug
Defining and Instantiating Classes
Lecture 2, CS61B, Fall 2024
Classes in Java
Interactive Debugging
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.
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, Fall 2024
Classes in Java
Interactive Debugging
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, Fall 2024
Classes in Java
Interactive Debugging
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!");
}
}
}
Practice Question
Lecture 2, CS61B, Fall 2024
Classes in Java
Interactive Debugging
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
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
Interactive Debugging
Lecture 2, CS61B, Fall 2024
Classes in Java
Interactive Debugging
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.
Goal: Larger Than Four Neighbors
Lecture 2, CS61B, Fall 2024
Classes in Java
Interactive Debugging
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:
public static Dog[] largerThanFourNeighbors(Dog[] dogs)
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?
public static Dog[] largerThanFourNeighbors(Dog[] dogs)
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?
public static Dog[] largerThanFourNeighbors(Dog[] dogs)
Using the Debugger
Lecture 2, CS61B, Fall 2024
Classes in Java
Interactive Debugging
Setting Breakpoints
Inspecting Program State
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
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
Continue
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