107 views
# Lecture 6 (from FP) -- Lists, Loops, Public, Private ## Motivating Question What if we wanted an arbitrary number of animals at the zoo? How do we create and manipulate lists in Java? ## Creating a List Let's replace our two specific IAnimals with a list of IAnimals in the `Zoo` class. ```java import java.util.LinkedList; public class Zoo { public LinkedList<IAnimal> allAnimals; public Zoo() { this.allAnimals = new LinkedList<IAnimal>(); } ... } ``` Note the `new LinkedList<>()` inside the constructor: this code creates the object that represents the list. In order to use lists, we need the `import` that appears above the `Zoo` class (it will go at the top of the file). ### A Constructor That Adds Animals to the List If you want to preserve the old constructor that takes two specific animals, we can modify it to add those two animals to the list instead. Java has an `add` method that puts an item into a list. ```java public Zoo(IAnimal ani1, IAnimal ani2) { this.allAnimals = new LinkedList<>(); // Add our two animals this.allAnimals.add(ani1); this.allAnimals.add(ani2); } ``` Unlike in Racket, Pyret, or ReasonML, the `add` method actually changes the contents that are inside a list; in these other languages, you get back a new list that contains both the new element and whatever was there before. In Java (as in Python), using `add` destroys the old list. ## Processing Lists In Java, we process lists by walking through them one element at a time (a process called "iteration") rather than use recursion. Here's the iterative approach: ```java // Write a method to determine how many non-normal-size animals are in the zoo public int nonNormalCount() { int count = 0; for (IAnimal ani : this.allAnimals) { if (!(ani.isNormalSize())) { count = count + 1; } } return count; } ``` The four pieces of the iteration pattern are as follows: **Part 1 — `int count = 0;`** Set up the variable for the result. The *starting value* (here, `0`) will be the result if the list is empty. **Part 2 — `for (IAnimal ani : this.allAnimals) {`** "Iterate over" (or "loop over") all objects in `allAnimals`. `IAnimal` states the type of the list elements, `ani` names the individual list items in turn, and `this.allAnimals` is an expression that returns the list to iterate over. **Part 3 — `count = count + 1;`** In the body of the loop, we update something — here, it's `count`, the variable we're using to keep track of the result. (This particular version also could be written as `count += 1` or `count++`.) **Part 4 — `return count;`** When the loop ends, either return the result you built up or use it in a subsequent computation. ## An Error: Reaching Into an Animal's Fields Here's a proposed method for computing the average length of animals: ```java for(IAnimal ani : this.allAnimals) { if (ani.isNormalSize()) { sum = sum + ani.length // ERROR! ``` The marked expression `ani.length` is an error. This is a problem for two big reasons: 1. Since the class `Zoo` can access an animal's fields, it can also *modify* them! In a big system, we usually don't want this, since it means other parts of the code (written by different people) can modify our data! 2. `ani` has type `IAnimal`. Not all animals have a `length` field, only those that extend `SizedAnimal`! (`FruitFly`, for example, does not) ## Public/Private/Protected Fields (Addresses Problem 1) ```java public abstract class SizedAnimal implements IAnimal { private int length; ``` - If you mark a field or method as `private`, it can't be used outside of that class (in this case, `SizedAnimal`). - A private field can ONLY be used within the class where it is declared (i.e., `SizedAnimal`). Not even `Dillo` or `Shark` could use it in this form! - A field or method marked as `protected` can only be used by the class where it's declared, and its subclasses. *(This is the best choice for the Zoo example.)* - Marking `length` as protected would allow it to be used by `Dillo`, `Boa`, `Fish`, or anything that extends these (like `Shark`). - A field or method marked `public` can be used by any other class. - For fields, this means that other parts of the code can modify them! - Thus, in Java we usually mark fields as private unless we need them to be public. ### So How Do We Give Zoo Access to the `length` Field? As authors of the `SizedAnimal` class, we get to decide how other classes can access our fields. If we want other classes to be able to get an animal's length, we can write a method like this (in `SizedAnimal`): ```java public int getLength() { return this.length; } ``` The idea is that we ONLY do this when we decide that a particular field should be exposed. If you have done any object-oriented programming before, you may have heard a rule that you should create a `get` method like this for every field (or, that you should create a corresponding method to `set` the value of a field). Never create these by default: if you do, you're undoing reasons for making the field private in the first place. Only create one of these methods if your computation actually needs it. ## Problem 2: Not All Animals Have `getLength()` We just added `getLength` to `SizedAnimal`, which provides the method for all animals that extend `SizedAnimal`. But in the `Zoo` class, our list is of type `IAnimal`. What does Java know about `IAnimal`? ```java public interface IAnimal { // Like a contract that specifies methods that // all animals should have /** * * @return true if this animal has a normal size */ public boolean isNormalSize(); ``` At this point, all we can do with an `IAnimal` is call `isNormalSize`. To use `getLength()` we need to add it to our interface so that we can do this for all animals. Here's the most important bits; see the full posted code for details. ```java public interface IAnimal { // Like a contract that specifies methods that // all animals should have /** * * @return true if this animal has a normal size */ public boolean isNormalSize(); public int getLength(); // the newly added method } ``` With `getLength()` in the interface, the loop body now type-checks. Excerpt from `averageNormalLength()`: ```java // ... for(IAnimal ani : this.allAnimals) { if (ani.isNormalSize()) { sum = sum + ani.getLength(); } } // ... ```