Wednesday, January 17, 2007

Lecture 6

Objects vs. Primitives
  • 4 integer types - byte, short, long, int
  • 2 floating point types - float, double
  • 1 Boolean
  • 1 char
  • remember if A and B are objects and we write a=b
  • then a is A is a reference to B, A is NOT a copy of B
  • the exact opposite occurs when A,B are primitives
  • reference passing can happen in 3 ways:
    • a=b
    • parameter passing
    • return value passing
  • privacy violations can occur unless you are careful
Defensive Copying

  • Defensive copying is used to force all interactions w/ private fields to go through the public interface (example: through the class methods)
  • Defensive copies of mutable objects are always performed when an object is into or out of a class (Shield the reference from the outside world)
  • Constructors (in) - as parameters
  • Accessors(out) - as return values
  • Mutators (in) - as parameters
Example
myclass(x)
public myclass accessor(){
return x; //BAD!!
//this is bad becuase it passes the reference outside the class

myclass copy_of_x = new myclass(x);
return copy_of_x; //OK!!

Example 2

myclass(x)
public void mutator(myclass x_in){
x=x_in; //BAD!!
//because whoever called the mutator pertains a reference to x_in, which is a direct reference of x.

myclass copy_of_x_in = new myclass(x_in)
x=
copy_of_x_in // GOOD!!

Immutable Classes
  • an immutable class is a class whose private fields cannot be changed after construction
  • a mutable class is the opposite and can change after construction
  • an immutable class has the following properties
    • all instance fields are private
    • no mutators
    • and either
      • all private/instance fields are primitives
      • or themselves a primitive
    • or
      • defensive copies are always made of any mutable classes
  • if a class is truly immutable then defensive copies do not need to be made of it
    • therefore it's perfectly OK to share references of mutable classes
    • this saves memory
  • Immutable classes do not require copy constructors
  • mutable classes MUST have copy constructors (for defensive copying)







2 comments:

Anonymous said...

Thank you.
This is very well organized.
I think this blog will become very handy during the exam period which is starting two weeks from now :)

If you could do me a favor and publish today's lecture (friday 19) i will be greatful.

Thanks again.

Jake said...

Lecture 7 is up, i have a couple hours between classes on mon, wed, fri, so it will usually be posted within a couple hours of the lecture.
Later
Jake
ps, go make a blogger account, it's nice to see names on here!