1 of 33

HW0

This lecture assumes you have completed homework 0. If you have not done so yet, complete HW0 and then come back.

2 of 33

Further Notes for Webcast Viewers

  • Any time I’m live coding, I advise you to pause frequently and try to anticipate my next move. You’ll probably learn more by trying to guess what I’m going to do rather than just watching me do it.

3 of 33

Announcements

  • Project 0 will be released this evening! Due next Friday, September 2nd at 11:59 PM.
    • To be completed on your own, no partners.
    • Though do take advantage of office hours!
  • Lab 1 is due Friday, September 2nd (double check), to allow for additional time for people joining the class late or with significant setup issues.

4 of 33

Announcements 2

Ed tips: See https://fa22.datastructur.es/materials/guides/ed/

  • Make sure to search for an answer before posting.

  • Make sure your question has enough information for someone to help.
    • Good question: https://imgur.com/a/6wUIR
      • Screenshots! Examples of what the anonymous poster has tried. And a followup explaining the resolution for other students.
  • Starting with project 0: If there’s a chance a staff member might need to look at your code, make sure your most recent code is pushed to github and provide a link in your post.
    • Make sure to use the “gitbugs” category for private debugging questions!

5 of 33

Announcements 3

Example of a bad question.

  • Doesn’t specify when the error is happening or what it is.
  • No discussion of what the student has already tried.

6 of 33

CS61B: 2022

Lec 2: Using and Defining Classes

  • Compilation
  • Defining and Instantiating Classes
  • Static vs. Instance Members
  • Managing Complexity with Helper Methods

7 of 33

Compilation

8 of 33

Compilation

The standard tools for executing Java programs use a two step process:

  • This is not the only way to run Java code.

Hello.java

Hello.class

javac

java

stuff

happens

Compiler

Interpreter

Why make a class file at all?

  • .class file has been type checked. Distributed code is safer.
  • .class files are ‘simpler’ for machine to execute. Distributed code is faster.
  • Minor benefit: Protects your intellectual property. No need to give out source.

Note: .class files are easily reversible into similar looking Java files.

You can learn more about all this in 61C and particularly 164.

9 of 33

Compilation and IntelliJ

The workflow that I just demoed is known as the “command line workflow”.

  • Uses the “javac” and “java” command line tools to explicitly compile and run our code.

In our course, we won’t use this workflow. Instead, we’ll use an Integrated Development Environment (IDE) called “IntelliJ” (see lab 1).

  • IDEs are essentially fancy text editors with features useful for programming.
  • Over the next four weeks you’ll get to know various features of IntelliJ.
  • Staff will only officially support use of IntelliJ.
    • If you want to use a plain text editor (e.g. Sublime Text) or another IDE (e.g. Visual Studio Code), we aren’t going to stop you. However, use of IntelliJ is very strongly recommended.
  • IDEs use javac and java under the hood to compile and run code.

10 of 33

Defining and Instantiating Classes

11 of 33

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!

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

}

}

12 of 33

Object Instantiation

Not all dogs are equal!

13 of 33

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

}

}

14 of 33

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.

These instances are also called ‘objects’

15 of 33

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.

16 of 33

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.

17 of 33

Arrays of Objects (assuming you’ve done HW0!)

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 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.

18 of 33

Static vs. Instance Members

19 of 33

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

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

}

20 of 33

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. �

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;

}

21 of 33

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.

22 of 33

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;

}

}

}

23 of 33

Answer to Question

Won’t go over in live lecture. Use the visualizer to see the solution at this link.

  • Or if you’re watching this video and can’t find the slides, the link is: http://goo.gl/HLzN6s

24 of 33

Managing Complexity with Helper Methods

25 of 33

Managing Complexity with Classes and Static Methods

Some obvious questions arise:

  • Why does Java force us to use classes?
  • Why have static methods at all?

The reason: To take choices away from the programmer.

  • Fewer choices means fewer ways to do things.
    • Example: Declaring a method static means you can’t use any instance variables in that method.
  • Fewer ways to do things often means less complexity.

26 of 33

Managing Complexity More Generally

IMO, a good foundational computer science course should primarily teach you to properly manage complexity.

  • This philosophy drives nearly all aspects of this 61B’s design.

Let’s cover one important idea that you’ll want to be using all throughout the course: helper methods.

  • Using helper methods lets you formalize the decomposition of large problems into small ones.
  • By focusing mental effort on a single task, there’s less room to make mistakes.

27 of 33

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.

  • Example: Can do tilt(NORTH) by creating tiltColumn and calling 4x.
  • Example: Can do tiltColumn by decomposing into more helper function(s).

tilt(NORTH)

28 of 33

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.

29 of 33

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?

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

30 of 33

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?

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

31 of 33

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!).

  • This code will be messy, hard to reason about, hard to debug.

32 of 33

Doing a Better Job

Now that you understand the problem, you might try coming up with a better solution.

  • Starter code on the next slide (copy and paste into IntelliJ).
  • By formally decomposing into helper methods, our code will be easier to read and understand, and easier to debug when things go wrong.

Or if you’d prefer, a solution available in this supplementary video:

33 of 33

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

}

}