Monday, January 22, 2007

Lecture 8

Scope of Variables

  • how far are the declared variables visible in code?
  • when is it safe to refuse variable names?
  1. Local variables within a method
    1. always applies to the method parameters
    2. the scope of local variables is the set of {} that contains the definition
    3. this is usually, but not always, the braces {} surrounding the entire method
    4. not allowed to have two variables of the same name within the same set of braces{}

Example
public void method(){ int x=o; int x=5; // illegal }

Example 2

public void method(){
x=0 //illegal

if (y==5)
{ int x = 0;
x=x+y;
}
else {
int x = 5;
}


  • x is only accessible through the scope of {} between if and else
  • putting x = 0 at the top is illegal because it is outside the desired scope

2. Local variables vs. Instance Fields


public class BankAccount{
Private double balance;
public void method ()
{
double balance; //legal
balance = 0; // legal - this is legal because local variables take precedence

this.balance = 0; // instance field relates to balance


3. Multiple Objects

  • methods of an object can see private fields of any object of that class

private double balance

public void method(BankAccount x){
balance = 0; //current object
x.balance = 0 // other object

// if user typed x.method(y) then x would relate to
balance = 0 and y would relate to balance = 0

Clone, shallow copies, deep copies
  • implement copy constructors to perform defensive copies which avoids privacy leaks
  • you may be tempted to use the method clone() as an easy copy constructor.
  • the only time to use clone() is if no copy constructor is defined.

example
MOWC a,b;
a = new MOWN();
b=a.clone(); // creates a shallow copy of a and store it in b

// this is similar to but not identical to using the copy constructor

what does clone do?
  • creates a bitwise copy of the object

Example

{ int a,b;
private myobject c;}
// my object is mutable}

//console
x = new MOWC():
//this example would give a reference to myobject c even if copied it will reference the same object instead of a new

  • two references
  • changes y to show up in x
  • privacy leak
  • this is a shallow copy
  • clone() implements a shallow copy, which does not respect the semantics of the object it copies
  • shallow copies can lead to a privacy leak
  • Deep Copy
    • implements a copy constructor

public class MOWC(MOWC in){
a = in.a;
b=in.b;
c= new myobject(in.c);
}
//this is the correct way to deep copy

  • shallow copy is safe if your object contains
    • primitives
    • immutable classes
  • deep copy is mandatory if object contains mutable classes
  • From Now On
    • properly implement a copy constructor for all mutable classes that you design
  • Only
    • use clone() if no copy constructor exists





No comments: