Wednesday, January 17, 2007

Lecture 5

Static Fields

  • an instance field is a field contained within each and every object of a particular class
  • a static field is a field for the entire class
    • one for the entire class
    • can access a static field w/o instantiating any objects
Example 1

  • can be used to store constants in a utility
private static double pi = 3.14
public static double getpi(){return pi;}

Example 2

  • Can use a static field to keep track of the number of instances of a class.
Caution about static: do not over use it
  • if you make everything static then objects and classes become meaningless
  • is will no longer be object oriented if static classes are only involved
Copy Constructor

  • a special kind of constructor that is used for copying objects
  • how do we create a new object that is a copy of an existing object?
Example

myobject x,y;
y=new myobject();
y=x; // this is bad!!!

  • this does not create a copy, it makes y another name for x. if i make changes to y, those changes also occur to x.
  • this also works both ways
  • Copy Constructor is the proper strategy
public class myobject {//two private fields: a,b
public myobject (myobject Source) {
//'Source' is the variable name
//copy constructor
a = source.a
b = source.b

x = new myobject();
y = new myobject(x);

}

  • this raises important points about Java objects:
    • the variable name is only a reference to the object. it does NOT contain the object itself
    • that's why y=x does not COPY
      • it makes y a reference to x
    • this is true for all objects in Java.
  • Exception to this rule
    • primitive types are not objects
      • byte (8 bit)
      • short (16 bit)
      • int (32 bit)
      • long(64 bit)
      • float(real number - 32 bit)
      • double(real number - 64 bit)
      • Boolean(true/false)
      • char(Unicode character)
Example

int x,y
x=5
y=x //this is OK, y will make it's own primitive w/ value 5 while x will also be separate from y

Mutable Classes
  • mutable classes have private fields that can change after instantiation
Immutable Classes
  • not allowed to change after construction
  • the reference is passed not only when = occurs, but also whenever objects are passed around
    • method parameters
    • return values
  • privacy violations occur unless care is taken to properly copy objects



No comments: