Working with objects

Modeling persons:

Figure 194. Instances of a Class Slide presentation
Instances of a Class

Figure 195. General class structure Slide presentation
General class structure

Figure 196. 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 197. Rectangle objects Slide presentation
Rectangle objects

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

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

Figure 199. Rectangle class and instances Slide presentation

Figure 200. Generated diagrams Slide presentation
Generated diagrams
Generated diagrams

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

Rectangle solidRectangle = new Rectangle();

...

Figure 202. 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 203. 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 204. Instance memory representation Slide presentation
Instance memory representation

Figure 205. 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 206. Checking for object presence Slide presentation
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);
}