questions? suggestions?. references references revisited what happens when we say: int x; double y;...

49
Questions? Questions? Suggestions? Suggestions?

Upload: jared-parsons

Post on 04-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Questions?Questions?Suggestions?Suggestions?

Page 2: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ReferencesReferences

Page 3: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

References RevisitedReferences Revisited

• What happens when we say:int x;

double y;

char c;

???

Page 4: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

We create variablesWe create variables

x

y

cVariable: Symbol plus a value

Page 5: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Assume that we haveAssume that we have

• class Box

• class LLNode

• as well as the usual suspects:

• class String, etc.

Page 6: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

What happens when we sayWhat happens when we say

Box b;

LLNode head;

String s;

Page 7: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

We create variablesWe create variables

b

head

s

Reference variables hold the location of objects. Ifthey aren't referencing anobject what is their value?

Reference variables hold the location of objects. Ifthey aren't referencing anobject what is their value?

Java keeps track of what type ofobject each reference can "point" to.

Java keeps track of what type ofobject each reference can "point" to.

Box

LLNode

String

Page 8: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Common Errors!Common Errors!

Box b = new Box(1, 2, 3);

.

.

.

Box b = new Box(4, 5, 6);

.

.

.

Page 9: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Should be:Should be:

Box b = new Box(1, 2, 3);

.

.

.

b = new Box(4, 5, 6);

.

.

.

Page 10: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Common Errors!Common Errors!

Box b = new Box(1, 2, 3);

b = anotherBox;

Page 11: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Should be:Should be:

Box b;

b = anotherBox;

Page 12: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Common Errors!Common Errors!

class Whatever

{

Box b;

// Constructor

public Whatever()

{

Box b = new Box(1, 2, 3);

Page 13: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Should be:Should be:

class Whatever

{

Box b;

// Constructor

public Whatever()

{

b = new Box(1, 2, 3);

Page 14: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Understanding ReferencesUnderstanding References

• Key to understanding– Arrays of Objects– Testing for Equality of Objects– Passing Objects to Methods– Assignment vs. Clone– etc.

For example...

Page 15: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Now, let’s consider WHY...Now, let’s consider WHY...

Understanding EqualityUnderstanding Equality

The key to understanding equality comes from knowing how Java handles references and primitives.

First, here’s the rule:

When comparing primitives, use ==, thus:

if ( iCount == iMaximum ) // etc.

When comparing objects, use .equals(), thus:

if ( box1.equals(box2) ) // etc.

Page 16: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Equality with Primitives:

int x;int y;x = 11;y = 3;

System.out.println(x == 11); // prints trueSystem.out.println(y = = 3); // prints trueSystem.out.println(x = = y); // prints false

x = y;

System.out.println(x = = 3); // prints trueSystem.out.println(y = = 3); // prints trueSystem.out.println(x == y); // prints trueSystem.out.println(x > y); // prints false

Testing Equality: PrimitivesTesting Equality: Primitives

11x: 3y:

3x: 3y:

Page 17: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

1. Are the references equal? Test with ==

In other words, are both references pointing to exactly the same object?

Considered to be the most stringent test for equality

Testing Equality: ObjectsTesting Equality: Objects

Page 18: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

2. Are the objects themselves equal?

The answer depends on your definition of equality!

Create an equals() method which compares the internal state of the object with another object passed in as a reference.

You need to create this method for every class where you will need to compare objects for equality

Testing Equality: ObjectsTesting Equality: Objects

Page 19: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ExampleExampleclass Rectangle {

int len, wid;

String name;

// Constructor and basic get/set methods not shown

public boolean equals(Object o) {

boolean retVal = false;

if(o instanceOf Rectangle)

{

Rectangle r = (Rectangle)o;

if(r.getLen() == len && r.getWid() == wid)

retVal = true;

}

return retVal;

}

Page 20: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ExampleExamplepublic static void main(String args[]) {

Rectangle r1 = new Rectangle(3,4,"Bob");

Rectangle r2 = new Rectangle(3,4,"Ted");

Rectangle r3 = new Rectangle(8,7,"Bob");

Rectangle r4 = r1;

String s = "Goofy";

System.out.println(r1.equals(r2));

System.out.println(r1.equals(r3));

System.out.println(r1.equals(r4));

System.out.println(r1.equals(s));

}

} // Rectangle

Page 21: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Recall the LLNodeRecall the LLNodepublic boolean equals(Object o) {

boolean retVal = false;

if(o instanceOf LLNode) {

retVal=getData().equals(((LLNode)o).getData());

}

return retval;

}Holy OO Gobbledy-Gook Batman!!!!

data

next

data

next

? ?

Page 22: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

The LLNodeThe LLNodepublic static void main(String args[]) {

LLNode n4 = new LLNode("delta", null);

LLNode n3 = new LLNode("gamma", n4);

LLNode n2 = new LLNode("beta", n3);

LLNode n1 = new LLNode("alpha", n2);

LLNode tester = new Node("beta", null);

System.out.println(n1.equals(tester));

System.out.println(n2.equals(tester));

System.out.println(n3.equals(tester));

System.out.println(n4.equals(tester));

}

Page 23: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Note!Note!

• The .equals() method in class Object is simply ==

Page 24: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ScopeScope

Page 25: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ScopeScopeLocal variables (declared as a part of method):

• Can be seen only from within their method.

• Outside of their method, their identifiers have no meaning.

Instance and Class variables (declared as part of a class, but not within a particular method):

• Can be seen from anywhere in the instance.

• This means they can be seen from within methods defined within the class without passing them to the method as parameters.

• May or may not be visible beyond (soon).

Within a method, local variable identifiers take precedence over instance variable IDers

Page 26: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

What we want:

class Person { String strName;

. . .

public void setName (String strName) {

strName = strName;

} // of setName

Inside the method, the String strName refers to the String in the method signature. This creates a problem: which strName is which?

Preventing Identifier AmbiguityPreventing Identifier Ambiguity

WRONG!

Page 27: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

What we get:

class Person { String strName;

. . .

public void setName (String strName) {

strName = strName;

} // of setName

Inside the method, the String strName refers to the String in the method signature. This creates a problem: which strName is which?

Preventing Identifier AmbiguityPreventing Identifier Ambiguity

WRONG!

Page 28: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Solutions:• Rename the formal parameter:

public void setName (String strNewStringName) {

strName = strNewStringName;

} // of setName

• Use the keyword this to refer to “current object”

public void setName (String strName) {

this.strName = strName;

} // of setName

Preventing Identifier AmbiguityPreventing Identifier Ambiguity

Preferred with Javadocs

Page 29: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ShadowingShadowing

Page 30: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ShadowingShadowing

• Refers to "hiding" something that still exists

• Simple case today

• Will come back to this topic during discussion on inheritance

Page 31: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ShadowingShadowingclass Widget {

public String namename;

public void someMethod(int i)

{

String namename; /* Shadows instance

variable */

namename = "Bob";

this.namethis.name = "Wally";

/* Accessing the shadowed

variable! */

Page 32: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ChainingChaining

Page 33: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Some ConstructorsSome Constructors

class Rectangle {

private int length, width;

private String name;

public Rectangle () {

setLength(0);

setWidth(0);

setName("Unnamed");

} // constructor

public Rectangle

(int l, int w) {

setLength(l);

setWidth(w);

setName("Unnamed");

} // constructor

public Rectangle

(int l, int w, String n){

setLength(l);

setWidth(w);

setname(n);

} // constructor

Page 34: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Constructor "Chaining"Constructor "Chaining"

class Rectangle {

private int length, width;

private String name;

public Rectangle () {

this(0,0,"Unnamed");

} // constructor

public Rectangle

(int l, int w) {

this(l, w,"Unnamed");

} // constructor

public Rectangle

(int l, int w, String n){

setLength(l);

setWidth(w);

setname(n);

} // constructor

Page 35: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Add a count?Add a count?

class Rectangle {

private int length, width;

private String name;

private static count = 0;

public Rectangle () {

setLength(0);

setWidth(0);

setName("Unnamed");

count++;

} // constructor

public Rectangle

(int l, int w) {

setLength(l);

setWidth(w);

setName("Unnamed");

count++;

} // constructor

public Rectangle

(int l, int w, String n){

setLength(l);

setWidth(w);

setname(n);

count++;

} // constructor

Page 36: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Add a count, simpler with "Chaining"Add a count, simpler with "Chaining"

class Rectangle {

private int length, width;

private String name;

private static int count = 0;

public Rectangle () {

this(0,0,"Unnamed");

} // constructor

public Rectangle

(int l, int w) {

this(l, w,"Unnamed");

} // constructor

public Rectangle

(int l, int w, String n){

setLength(l);

setWidth(w);

setname(n);

count++;

} // constructor

Page 37: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ArraysArrays

Page 38: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

ArraysArrays• An array may be declared to be:

– an array of primitives, or

– an array of objects (actually references!!!).

• The Array itself is an Object, even if the array contains primitives.

– (Array identifier references an object).

• If an array of objects, then:

– the array identifier is a reference to the array object

– each array element is a reference to an object of the class specified as elements

• Instantiating the array object does not instantiate the various element objects to which it refers.

• Element objects must be explicitly instantiated and initialized.

Page 39: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Example: Imagine a Flatware object which keeps track of: knives, forks and spoons.

class Flatware { int knives = 0; int forks = 0; int spoons = 0; public Flatware(int knives, int forks, int spoons) { setKnives(knives); setForks(forks); setSpoons(spoons); } // of constructor

/* We assume accessors, modifiers--getKnives(), setKnives(), etc. -- are implemented here */

} // of Flatware

ArraysArrays

Page 40: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Then, the code segment:

Flatware fw1 = new Flatware(10, 20, 30);Flatware fw2;

produces:

knives = 10forks = 20

spoons = 30fw1

fw2

ArraysArrays

Page 41: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

and the code segment:

Flatware[ ] flatwareArray = new Flatware[5];

produces:

which could then be initialized via:

int i;for ( i = 0; i < flatwareArray.length; i++){ flatwareArray[i] = new Flatware(10, 20, 30);} // of for loop initialization

flatwareArray

ArraysArrays

Page 42: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

giving:

flatwareArray

knives = 10forks = 20

spoons = 30

fw1

fw27 objects

7 objectsin total

in total6 Flatware

6 Flatware

objects

objects

ArraysArrays

knives = 10forks = 20

spoons = 30

knives = 10forks = 20

spoons = 30

knives = 10forks = 20

spoons = 30

knives = 10forks = 20

spoons = 30

knives = 10forks = 20

spoons = 30

Page 43: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

but the code segment:

int i;for ( i = 0; i < flatwareArray.length; i++) { flatwareArray[i] = fw1;} // of for loop initialization

produces:

flatwareArray

fw1

1 Flatware object...

1 Flatware object...

2 objects in total

2 objects in total

ArraysArrays

knives = 10forks = 20

spoons = 30

Page 44: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Review: Array CreationReview: Array Creation

• Declaration

int myInts[];

int[] myInts;• Instantiation

myInts = new int[10];• Declaration and instantiation:

int[] myInts = new int[10]; • Access to individual element

myInts[3] = 9;

x = myInts[4];• Static initialization

int[] myInts = {1,2,5,6,7,4};

Page 45: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Multi-Dimensional ArraysMulti-Dimensional Arrays

int[][] myTwoDimArray;

myTwoDimArray = new int[10][5];• Quiz Yourself!• Valid?

String[][] s;

s = new String[10][]; • Valid?

s = new String[][10];

//YES!

// NO!

Page 46: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

String s[][] = {{"Static", "multidimensional", "initialization", "of"}, {"arrays", "requires", "the", "use"}, {"of", "nested", "curlies"} };

Creates:

Static multidimensional Static multidimensional initialization:initialization:

Static

arrays

of

multidimensional

requires

nested

Initialization

the

curlies

of

use

(null)

Page 47: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Summary of ArraysSummary of Arrays

• Arrays• All arrays are objects (you have to declare,

instantiate, and initialize)• Arrays are either arrays of primitive

elements (e.g. int) or arrays of objects (really references to objects)

• Arrays are statically sized: you can’t change length after

declaration; arrays know their own length– Use Array.length in for loops to avoid “off-by-one”

errors

• 2D arrays are arrays of arrays

Page 48: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Questions?Questions?

Page 49: Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???