Working with objects

Intention:

Figure 219. Representing two-dimensional points Slide presentation
final Point
   p1 = new Point(1, 1),
   p2 = new Point(5, 4);

IO.println("The distance from " + p1 + " to " + p2 + " is " + p1.distance(p2));
The distance from (1|) to (5|4) is 5.0

Figure 220. General class structure Slide presentation
General class structure

Figure 221. What's a class anyway? Slide presentation

In object oriented languages classes:

  • are blueprints for objects.

  • contain attributes and methods.

  • allow for implementation hiding.

  • allow for tailored access to methods and attributes.


Figure 222. Rectangle objects Slide presentation
Rectangle objects

Figure 223. A class describing rectangles Slide presentation
public class Rectangle {
  int width;
  int height;

  // solid or dashed:
  boolean hasSolidBorder;
}
A class describing rectangles

Figure 224. Rectangle class and instances Slide presentation

Figure 225. Generated diagrams Slide presentation
Generated diagrams
Generated diagrams

Figure 226. The new operator: Creating rectangle instances Slide presentation
Rectangle dashedRectangle = new Rectangle();

Rectangle solidRectangle = new Rectangle();

...

Figure 227. Syntax creating instances Slide presentation
new class-name ([argument 1[, argument 2] ...] )
Wording examples:
  • Create an instance of class Rectangle.

  • Create a Rectangle object.

  • Create a Rectangle.


Figure 228. Assigning attribute values to class instances Slide presentation
Rectangle dashedRectangle = new Rectangle();

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

Syntax accessing object attributes:

variable.attributeName = value;

Figure 229. Instance memory representation Slide presentation
Instance memory representation

Figure 230. References and null Slide presentation
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)
Exception in thread "main" java.lang.NullPointerException
  at de.hdm_stuttgart.mi.classdemo.App.main(App.java:17)

Figure 231. Checking for object presence Slide presentation
Rectangle r;

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

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