CS II Lesson 8

Professor Abdul-Quader

Project 1 Discussion / Intro to Classes

Project Discussion

Questions?

Simple Ideas

  • Start with simple ideas
  • If you can get there in one move, do it.
  • If not?
  • Simple idea that works: pick a random move.
    • Program loops around and tries again.

Complicated Ideas?

  • Get something that works first
  • You only have 3.5 more days (Sunday night).
  • If you have time, figure out how to optimize:
    • Test it out as much as possible
    • Find all the edge cases that your code doesn’t handle
    • Try to handle them
    • More if statements?
    • Elegant idea that solves all your problems? (Maybe not.)

Presentation 1

  • Next 2 weeks: demo your project.
  • Give a “big picture” explanation of the algorithm for how you solved the problem.
  • Show / explain how your code implements that algorithm.
  • Sign-ups now.

Classes

Last time:

  • ArrayList is a class.

  • We can use the ArrayList class as the data type for our variables.

     ArrayList<Integer> list = new ArrayList<>();
     ArrayList<Integer> list2 = new ArrayList<>();

Classes

ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
  • list and list2 are different objects of type ArrayList
  • What does new do?

Instantiation

  • The new keyword instantiates the ArrayList object.
  • Instantiation: creating a new object of that type in memory.
  • What does this involve?

Constructors

Another way to define ArrayLists:

ArrayList<String> list = new ArrayList<>(25);
  • ArrayList has multiple constructors
  • Constructor: special method that is called when we the object is created
    • In particular, when the new keyword is used.
  • Used to initialize the data type.

Instance Methods

ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
list.add(1);
System.out.println("List 1 size: " + list.size());
System.out.println("list 2 size: " + list2.size());

What does this print out? Why?

Instance Methods

  • list and list2 are different objects
    • Keep track of different arrays in memory!
    • The arrays have different elements!
    • The arrays may have different sizes!
  • size is an instance method.
    • as opposed to a static method
  • instance methods: methods which act on specific objects
    • not on the class as a whole!
  • syntax: object.method(parameters)

New data types?

How do we define our own data types?

  • Define a class: public class MyClass
  • A class is a template for a data type.
  • In the class:
    • Define a constructor to initialize your data
    • Define instance methods to act on that data
    • How do we specify the data? instance variables
  • Outside of the class: use the class!
MyClass m = new MyClass();
m.someMethod();

Data / Behavior

  • Objects encapsulate data and behavior:
  • integer variable:
    • data: actual number it represents
    • behavior: add, subtract, etc.
  • ArrayList variable?
    • data?
    • behavior?
  • User-defined types? often:
    • data: instance variables
    • behavior: instance methods

toString and equals

Special methods that every class defines.

ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
list1.add(10);
list2.add(10);
if (list1 == list2) {
    System.out.println("The lists refer to the same object");
} else if (list1.equals(list2)) {
    System.out.println("The two lists have the same contents:");
    System.out.println(list1.toString());
    // technically, we could just do:
    // System.out.println(list1);
}

Designing classes

Create a new file, call it “Time.java”. Create the class:

public class Time {

}

Instance Variables

Inside the class, we can declare our instance variables, constructors, and instance methods. Declare three new variables:

private int hour;
private int minute;
private String amPm;

These are instance variables. Each instance of the Time class will have their own variables (independent of all the other instances).

Constructors

Now let’s give our class a constructor. We need an hour, minute, and whether it is AM or PM actually initialize our instance variables, so let’s pass them in as parameters.

public Time(int currentHour, int currentMinute, String amOrPm) {
    hour = currentHour;
    minute = currentMinute;
    amPm = amOrPm;
}

Using the class

In App.java:

public class App {
    public static void main(String[] args) {
        Time time = new Time(11, 2, "AM");
        System.out.println(time); // this is not so great
    }
}

What happened?

toString

  • println calls the toString method on the object.
  • Built-in toString method doesn’t output something very useful.
  • So: we can implement it ourselves
public String toString() {
  // what should go here?

}

Exercise

Implement the toString method. (Remember the issue if minute < 10?)

This method should return a String. It should not output anything!

Recap

  • Classes are templates for data types.
  • Declare a class: name public class MyClass in file MyClass.java
  • Declare instance variables.
  • Define your constructor(s)
  • Define your instance methods, like toString

Video

Problem?

Time time = new Time(13, 75, "Go away!");
System.out.println(time);
  • Is there a way we can get it to not work?
  • What happens when you create an ArrayList with a negative size?
    • Throws an IllegalArgumentException!
    • We can do that too!

Error Checking

public Time(int currentHour, int currentMinute, String amOrPm) {
    if (currentHour < 1 || currentHour > 12) {
        throw new IllegalArgumentException("hour must be between 1 and 12");
    } else {
        hour = currentHour;
    }
    ...
}
  • Yes, this will crash the program.
  • Not Time’s problem.
  • It’s a main method problem: make sure you validate before creating a Time object.
  • More on handling exceptions later this semester.

Magic Numbers

  • We know that the hour needs to be between 1 and 12 by common sense. But it’s bad practice to use literals or “magic numbers”.
  • Instead, we should use constant class variables, which have names which are easier to understand as we read the code (see: Think Java, 3.4).

Constant Class Variables

  • A class variable is a static variable: created once for the class as a whole (not created when constructors are called).
  • To make a variable constant (meaning it can’t be changed after it is created), we use the final keyword. Here is an example:
// convention: constants are UPPER_CASE
public static final int MIN_HOUR = 1;

Exercise

Clean up your constructor so that it checks if the hour, minute, and “AM” or “PM” variables are valid. Use constant class variables so that there are no “magic values”.

Visibility

Variable declarations in Time class:

    public static final int MIN_HOUR = 1;
    public static final int MAX_HOUR = 12;
    public static final int MIN_MINUTE = 0;
    public static final int MAX_MINUTE = 60;
    public static final String AM = "AM";
    public static final String PM = "PM";

    private int hour;
    private int minute;
    private String amPm;

  • Our constants are public?
  • Our instance variables are private?
  • toString is public?
  • Constructor: public Time(...).
  • Some public / some private?

Public vs private

Java has several different visibility modifiers:

  • public: this item (variable, method, constructor) can be used in code anywhere
  • protected: …
  • default visibility (ie, leave out the words public or private): …
  • private: this item can be used in code only in the same class

Rule of thumb

  • Make everything as private as you can.
  • Restrict how others use your class.
  • That way, you control how they will use it, and can predict / plan for bad behavior.

Bad Example

If the instance variables are public:

Time t = new Time(11, 59, Time.AM); // "11:59 AM"
t.hour = 53;
t.minute = -7;
t.amPm = "Hah! I tricked you!";
System.out.println(t);
  • Got around all of our error-checking!
  • What should we do instead? How would we print out just the hour?

Video

Upcoming

  • Project 1: due Sunday night.
  • Reading: chapters 9 - 11.
  • Quiz 2: next Thursday.
  • Project 1 presentations / demos: starting Monday in class.
// reveal.js plugins