5: Objects & References
We will look more closely at the object-oriented programming and the implications of instantiated objects.

Learning Targets

    I can describe what it means to be an object-oriented programmer.
    I can describe the difference between values and references.

Class Vocab

Object-Oriented Programming

Why don't we list all of our code in one long file? How do we start to organize big projects? We start with objects. Already we've been using a class with a main method as its starting point. All of our methods have been static. What if we wanted to make a game with a lot of monsters? We can define our own Monster class and create as many instances of that object as we need in the game. We can't use static methods anymore as a result.

Let's try out a simple game in class using while-true loop and a Monster.

Primitives and Refs

Practice.java
1
import java.util.ArrayList;
2
3
public class Practice {
4
5
public static void main(String[] args) {
6
7
// create a primitive
8
int myPrimitive = 5;
9
// pass it by value to a method that adds one to the item.
10
addOne(myPrimitive);
11
// print the unchanged value of the primitive
12
System.out.println("Primitive: " + myPrimitive);
13
14
// instantiate a list and store the reference to it in myRef
15
ArrayList<Integer> myRef = new ArrayList<>();
16
// add the value 5 to a new Integer
17
myRef.add(5);
18
// pass it by reference to a method that adds one to the first element in the list
19
addOne(myRef);
20
// print what's now in the first spot of the object that was passed by reference
21
System.out.println("Reference: " + myRef.get(0));
22
23
} // closes main
24
25
public static void addOne(ArrayList x) {
26
// get the current value of the first item in the list, convert to int
27
int current = (int)x.get(0);
28
// set the first item's value to one more than its current
29
x.set(0, ++current);
30
}
31
32
public static void addOne(int x) {
33
++x;
34
}
35
36
} // closes the class
37
Copied!
References are links to the original. Passing by value makes a copy

Intro to ArrayLists

ArrayLists are introduced in this section because they're objects themselves. They illustrate some of the differences we see when working with objects. Instead of arrays when we can access an element just by printing someCollection[x], we now need to use someOtherCollection.get(x). Let's get into these differences.

Different Kind of Loop

Because ArrayLists are only accessible through methods, you can use the same type of access[index] you can with an array. Here's what a simple traversal looks like with a good ol' array:
1
int[] myArray = {5, 10, 15, 20};
2
for(int x = 0; x < myArray.length; x++){
3
System.out.println(myArray[x]);
4
}
Copied!
Notice how I used length as a property not as an accessor method() and I accessed an element from the collection using [brackets]. Now let's take a look at an ArrayList:
1
List myList = new ArrayList<Integer>();
2
myList.add(5); // I could loop and add all these
3
myList.add(10);
4
myList.add(15);
5
myList.add(20);
6
for(int x = 0; x < myList.size(); x++){
7
System.out.println(myList.get(x));
8
}
Copied!
There's a couple important things happening above you should look closely at:
    Notice how I declared a List and then turned it into an ArrayList? It wouldn't have worked if I tried to do new List because a List is abstract. It's like mammal. You can tell the computer that you'd like to make a new mammal named x and it should run the new Dog() constructor. That's a polymorphic declaration. Use a general ancestor as a type and then be more specific during the constructor.
    If you look inside the ArrayList class programmed inside our Java library, you'll notice it has an array at its core. It's a wrapper for an array. So there is a .length property that's relevant to its internal, private programming. Every time you .add(something) to an ArrayList it destroys its old array and copies all the content to a new, longer array. So .length is serious business. Since that's occupied, we use the .size() accessor method to retrieve the length of an ArrayList.

SecureList: An Example

What's the point of creating our own objects? How does an ArrayList differ from an array in practical implementation? Let's go through an example project to help iIllustrate these concepts.

What is a SecureList?

SecureLists are made up. They're a silly object that provides an extra layer of "security" by storing your list of 12 names in two different objects, an array and an ArrayList. Does that actually provide additional security? No, not really. But let's pretend it does so you have an opportunity to work with an array and an ArrayList simultaneously.
Let's set up your project with the following files:
App.java
SecureList.java
1
/*
2
* To change this license header, choose License Headers in Project Properties.
3
* To change this template file, choose Tools | Templates
4
* and open the template in the editor.
5
*/
6
7
import java.util.Scanner;
8
9
public class App {
10
11
// from a static method, we'll create instances of our made-up object
12
public static void main(String[] args) throws Exception {
13
14
System.out.println("Let's build a list of names to test.");
15
Scanner s = new Scanner(System.in);
16
17
// our example container
18
String[] testList = new String[12];
19
20
// build an example list to work with
21
System.out.print("Would you like to enter names? (y/n): ");
22
if(s.nextLine().equals("y")){
23
// populate the array with names from user
24
for(int x = 0; x < 12; x++){
25
System.out.print("\nInsert name at index " + x + ": ");
26
testList[x] = s.nextLine();
27
System.out.println();
28
}
29
} else {
30
// populate the array with just numbers
31
for(int x = 0; x < 12; x++){
32
testList[x] = "Student #" + x;
33
}
34
}
35
36
System.out.println("\n----- SecureList Unit Tests ------\n");
37
38
// test the constructor
39
SecureList test1 = new SecureList(testList);
40
41
// test title mutator and accessor
42
System.out.println("\nTITLE TEST: \n");
43
test1.title("Demo"); // mutator
44
System.out.println(test1.title()); // accessor
45
46
// implicitly call the .toString() method
47
System.out.println("\nPRINT TEST: \n");
48
System.out.println(test1);
49
50
// draw a random name from the list
51
System.out.println("\nGET RANDOM: \n");
52
System.out.println(test1.getRandom());
53
54
// check that each element in both collections match
55
System.out.println("\nIS SECURE: \n");
56
System.out.println(test1.isSecure()); // should print "true"
57
58
// get the first name in the list
59
System.out.println("\nGET STUDENT 0: \n");
60
System.out.println(test1.getName(0));
61
62
// get the first name in the list using the seat number not the index
63
System.out.println("\nGET SEAT 1: \n");
64
System.out.println(test1.getStudentBySeat(1));
65
66
// randomize the order of the names
67
System.out.println("\nSHUFFLE: \n");
68
test1.shuffle();
69
System.out.println(test1);
70
71
}
72
}
Copied!
1
/*
2
* To change this license header, choose License Headers in Project Properties.
3
* To change this template file, choose Tools | Templates
4
* and open the template in the editor.
5
*/
6
7
import java.util.ArrayList;
8
9
/**
10
* Doubles the protection of your data by storing your 12 names in both an array
11
* and an ArrayList
12
*/
13
public class SecureList {
14
15
// ENCAPSULATED INSTANCE VARIABLES
16
// a var for the title String
17
18
// uninitialized String Array
19
20
// uninstantiated ArrayList typecast to String
21
22
23
// -----------
24
// CONSTRUCTORS
25
// -----------
26
27
/**
28
* This is the basic constructor that initializes all the instance variables
29
*/
30
public SecureList(){
31
// create a blank title
32
title = "";
33
// create a blank array of Strings
34
nameArray = new String[12];
35
// instantiate an ArrayList and then loop and add 12 blank Strings
36
nameList = new ArrayList<String>();
37
for(int i = 0; i < 12; i++) nameList.add("");
38
}
39
40
/**
41
* Extracts names from an ArrayList to store in both class containers
42
* @param nameList : starting names
43
*/
44
public SecureList(ArrayList<String> nameList){
45
// call the first constructor to setup the blank stuff
46
this();
47
48
// copy the data from the given list
49
50
}
51
52
/**
53
* Extracts names from an array to store in both class containers
54
* @param nameArray : starting names
55
*/
56
public SecureList(String[] nameArray){
57
// call the first constructor to setup the blank stuff
58
this();
59
60
// copy the data from the given array
61
}
62
63
// -----------
64
// ACCESSORS
65
// -----------
66
67
/**
68
* Accessor method for the title instance variable
69
* @return this.title
70
*/
71
public String title(){
72
73
}
74
75
/**
76
* After checking that the names between the two strings
77
* @param n : the zero-indexed location of the name
78
* @return
79
*/
80
public String getName(int n){
81
// use the isSecure method to check n
82
if(!isSecure(n)){
83
System.out.println("NOT SECURE");
84
return null;
85
}
86
87
// return the name in the index location of n
88
89
}
90
91
/**
92
* Wrapper for the getName method that is NOT zero-indexed
93
* @param s: Seat location
94
* @return
95
*/
96
public String getStudentBySeat(int s){
97
98
}
99
100
// -----------
101
// MUTATORS
102
// -----------
103
104
/**
105
* Modify this instance's title property
106
* @param title : new label for this secure list object
107
*/
108
public void title(String title){
109
110
}
111
112
/**
113
* Change the name of both collections at a given index location
114
* @param n : index location to target
115
* @param name : new name value to set
116
*/
117
public void changeName(int n, String name){
118
119
}
120
121
// -----------
122
// UTILITIES
123
// -----------
124
125
/**
126
* Checks if the given index location is a blank "" string
127
* @param n : index location to check
128
* @return : true if the index location had a length of zero
129
*/
130
public boolean isEmpty(int n){
131
132
}
133
134
/**
135
* Returns the comparision between the two Strings in the container at position n
136
* @param n : the zero-indexed location in the collection to check
137
* @return true if the two Strings .equal
138
*/
139
public boolean isSecure(int n){
140
141
}
142
143
/**
144
* Traverses the length of the collection and checks in location is secure.
145
* If any is found insecure, it returns false
146
* @return list integrity
147
*/
148
public boolean isSecure(){
149
// loop
150
// if insecure at that postion, return false
151
152
// if you make it through the loop safely, return true
153
}
154
155
/**
156
* Draws a random index location and returns the name at that location
157
* @return : the String value at a random index location
158
*/
159
public String getRandom(){
160
// generate a random number from 0 up until but not including the length
161
162
// return the call to the getName method
163
}
164
165
/**
166
* Randomizes the location of all the Strings using the Selection Shuffle
167
* algorithm
168
*/
169
public void shuffle(){
170
171
}
172
173
/**
174
* Traverses name collection, printing the seat location followed
175
* by the name
176
*/
177
@Override
178
public String toString(){
179
180
}
181
182
}
Copied!
Last modified 10mo ago