CPSC 210

B3: Classes & Objects

Learning Goals

  • Distinguish between primitive and reference variables
  • Use an ArrayList to store data
  • Identify "active" (or: instantiated) objects at a point of execution in code
  • Use the IntelliJ debugger 🐞 to step through code and inspect variables

OO Terminology Reminder

Constructors

(special type of method)

Methods

Fields

ArrayList in Java

  • Used to store data of arbitrary size
  • In Racket, you treated (listof X) as built-in, where X is a type parameter
  • Similarly, ArrayList<E> is part of the Java library and E is a type parameter that represents the type of data to be stored in the list

1

2

3

4

0

...

Types in Java

  • Java primitive (built-in) types; they "fit" in a variable
    • byte, short, int, long, float, double, boolean, char
      •  
  • All other variable types are reference types
    • They are used to refer to an object
      •  

Person
object

Person p = new Person();

 p

int count = 4;

 count     4

Lecture Ticket Review

Which of the following are valid Java code segments?

int y = 3;
A a;
a = new A();
B b = make B();
int x = 3;
x.add(1);

Q1

public class Person {
    private String name;

    public Person () {
        this.name = "Unnamed Person";
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("Now my name is " + 
        	this.name);
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person harry = new Person();
        Person hermione = new Person();
        harry.setName("Harry");
        hermione.setName("Hermione");

        ArrayList<Person> people = 
        	new ArrayList<>();
        people.add(harry);
        people.add(harry);
        people.add(hermione);

        Person someone = people.get(1);
        someone.setName("Ron");
    }
}

Q2

Lecture Lab: Buggy Pizza

  1. Look inside the Pizza class
    • What is the constructor?
    • What are the fields?
    • What are the methods?

2. When you run your PizzaTopper project, it should print out:

  

 

And instead you’re getting:

  

 

There are a couple of things wrong! Make hypotheses for each bug and solve as you go!

pizza1 pizza has 1 toppings
pizza2 pizza has 2 toppings
null has 0 toppings
null has 0 toppings

Extra: Git Branching

Branch: main

Branch: myfavoriteanimal

Create
Branch

Merge
Branch

Commits

B3: Classes & Objects

The End - Thank You!

Made with Slides.com