Chapter 3: What I learned....
Within chapter 3, it detailed primitive AND reference variables and what they do and what they are defined as. The bits representing the variable is the primitive variable, but the bits representing a way to get an object on the heap is known as a reference variable. Also, if you odnt have an object assigned to the reference variable, then it is deemed null. As well as learning about these fun variable types, looking at the dog code (seen below) it taught me what arrays look like and how they should be used. Very useful indeed!
String name;
public static void main (String[] args) {
// make a Dog object and access it
Dog dog1 = new Dog();
dog1.bark();
dog1.name = “Bart”;
// now make a Dog array
Dog[] myDogs = new Dog[3];
// and put some dogs in it
myDogs[0] = new Dog();
myDogs[1] = new Dog();
myDogs[2] = dog1;
// now access the Dogs using the array references
myDogs[0].name = “Fred”;
myDogs[1].name = “Marge”;
// Hmmmm... what is myDogs[2] name?
System.out.print(“last dog’s name is “);
System.out.println(myDogs[2].name);
// now loop through the array and tell all dogs to bark
int x = 0;
while(x < myDogs.length) {
myDogs[x].bark();
x = x + 1;
}
}
public void bark() {
System.out.println(name + “ says Ruff!”); }
public void cat();
public void chaseCat()
}
No comments:
Post a Comment