Working with objects

Figure 211. Creating rectangle instances Slide presentation Create comment in forum
Rectangle dashedRectangle = new Rectangle();

Rectangle solidRectangle = new Rectangle();

...

Figure 212. Syntax creating instances Slide presentation Create comment in forum
variable = new (class-name)
Wording example:
  • Create an instance of class Rectangle.

  • Create a Rectangle object.

  • Create a Rectangle.


Figure 213. Assigning attribute values Slide presentation Create comment in forum
Rectangle dashedRectangle = new Rectangle();

dashedRectangle.width = 28;
dashedRectangle.height = 10;
dashedRectangle.hasSolidBorder = false;

Syntax accessing object attributes:

variable.attributeName = value;

Figure 214. Memory representation Slide presentation Create comment in forum
Memory representation

Figure 215. References and null Slide presentation Create comment in forum
Rectangle r = new Rectangle();// Creating an object

r.width = 28; // o.K.

r = null;// removing reference to object

r.width = 28; // Runtime error: NullPointerException (NPE)

Figure 216. Checking for object presence Slide presentation Create comment in forum
Rectangle r;

... // possible object assignment to variable r.

if (null == r) {
  System.out.println("No rectangle on offer");
} else {
  System.out.println("Width:" + r.width);
}