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.
directs the run-time system to create a new object.
Creating an object consists of three actions:
new is like a system defined method call that does all of the above.
h = new Hello1(s);
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.)
Allows you to refer to class-level fields and methods from within a method.
this.h = 55;
refers to the field named h, even if there also happens to be a parameter or local variable named h.
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”);