HW0
This lecture assumes you have completed homework 0. If you have not done so yet, complete HW0 and then come back.
Further Notes for Webcast Viewers
Announcements
Announcements 2
Ed tips: See https://fa22.datastructur.es/materials/guides/ed/
Announcements 3
Example of a bad question.
CS61B: 2022
Lec 2: Using and Defining Classes
Compilation
Compilation
The standard tools for executing Java programs use a two step process:
Hello.java
Hello.class
javac
java
stuff
happens
Compiler
Interpreter
Why make a class file at all?
Note: .class files are easily reversible into similar looking Java files.
You can learn more about all this in 61C and particularly 164.
Compilation and IntelliJ
The workflow that I just demoed is known as the “command line workflow”.
In our course, we won’t use this workflow. Instead, we’ll use an Integrated Development Environment (IDE) called “IntelliJ” (see lab 1).
Defining and Instantiating Classes
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();
}
}
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("arooooooooooooooo!");
}
}
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.
These instances are also called ‘objects’
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.
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 (assuming you’ve done HW0!)
To create an array of objects:
Example:
After code runs:
Dog of size 8 | Dog of size 20 |
0
1
dogs =
Dog[] dogs = new Dog[2];
dogs[0] = new Dog(8);
dogs[1] = new Dog(20);
dogs[0].makeNoise();
Yipping occurs.
Creates an array of Dogs of size 2.
Static vs. Instance Members
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 vs. Non-static
A class may have a mix of static and non-static members.
Question: Will this program compile? If so, what will it print?
< 10:
yip
< 30:�bark
>=30:
woof
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;
}
}
}
Answer to Question
Won’t go over in live lecture. Use the visualizer to see the solution at this link.
Managing Complexity with Helper Methods
Managing Complexity with Classes and Static Methods
Some obvious questions arise:
The reason: To take choices away from the programmer.
Managing Complexity More Generally
IMO, a good foundational computer science course should primarily teach you to properly manage complexity.
Let’s cover one important idea that you’ll want to be using all throughout the course: helper methods.
Example of a Complex Task from Project 0
In Project 0, you’ll implement a “tilt” function for the game 2048. A lot happens at once. Absolutely vital to decompose the problem into pieces.
tilt(NORTH)
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:
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?
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?
Writing largerThanFourNeighbors
Now let’s try it out!
Let’s make an attempt during lecture that will be all part of one big method (i.e. there are no helper methods!).
Doing a Better Job
Now that you understand the problem, you might try coming up with a better solution.
Or if you’d prefer, a solution available in this supplementary video:
Starter Code for Dog Problem
public class DogProblem {
public static Dog[] largerThanFourNeighbors(Dog[] dogs) {
return dogs;
}
public static void main(String[] args) {
Dog[] dogs = new Dog[]{
new Dog(10), new Dog(15),
new Dog(20), new Dog(15),
new Dog(10), new Dog(5),
new Dog(10), new Dog(15),
new Dog(22), new Dog(15),
new Dog(20)
};
Dog[] bigDogs1 = largerThanFourNeighbors(dogs);
/** When you run this program you should get "20 22" */
for (int k = 0; k < bigDogs1.length; k += 1) {
System.out.print(bigDogs1[k].weightInPounds + " ");
}
System.out.println();
}
}