Week 5, Notes 1

Reading this week is again review: 3.1, pp. 171-175 (The method main() in the class Transactions creates new Account objects and passes data for each object to the constructor for the Account class.), 5.5 (pp. 227-233).

Objects creating objects

Useful when one object is abstracting the functionality of more detailed objects, e.g., OneShape objects create Circle, Square, or Triangle objects, so the user doesn’t have to do it.

new keyword

directs the run-time system to create a new object.

 

Creating an object consists of three actions:

  1. Finding and allocating memory for the new object, creating the object in this memory, and putting the object in a default state
  2. Calling the appropriate constructor for the object
  3. Returning an object reference (or pointer)

 

new  is like a system defined method call that does all of the above.

Example

see demos/Week05Notes01

 

h = new Hello1(s);

 

  1. Create a new Hello1 object
  2. Call the Hello1 constructor that takes one String parameter to initialize the new object

 

Review dereferencing null pointers

Create a new MemoryAndScope object by passing  null to the MemoryAndScope constructor.

Call the  print() method on your new object.

Notice that blueJ highlights the following line in your MemoryAndScope source code:

        h.print();

·        The field  h is holding the value  null

·        null is the pointer that points to nothing

·        The  . following the  h means follow the pointer held in the field named  h

·        The null pointer doesn’t point to anything, so it cannot be followed to find a real object, so the Java runtime system gives a  null pointer exception and stops.  (blueJ then shows you the line in the source code where the problem occurred.)

 

this keyword

Allows you to refer to class-level fields and methods from within a method.

Referring to instance variables

this.h = 55;

 

refers to the field named h, even if there also happens to be a parameter or local variable named h.

Calling other methods defined in my class

this.myMethod(“string parameter”);

calls the method named myMethod supported by the current object.  It is rare to include the keyword  this to call a method in the current class, because leaving the  this off does the same thing, e.g.,

 

myMethod(“string parameter”);

Introduction to the debugger