SE450: Basics: Multiplicity [43/63] |
Multiplicities put constraints on number of references held by an object.
Recall java.util.List and java.io.BufferedReader.
+---------------+ | <<interface>> | * +--------+ | List |<>------>| Object | +---------------+ +--------+ +----------------+ 0..1 +--------+ | BufferedReader |<>----->| Reader | +----------------+ +--------+
Note: if mutiplicity is 1, then reference must be non-null when constructor terminates.
This may require that we throw and IllegalArgumentException if an argument to the constructor is null.
file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
package basics.checkargs; public class Main { private Main() {} static public void main (final String[] args) { //stdlib.Trace.graphvizShowSteps (true); stdlib.Trace.run (); try { System.out.println(new Person("bob")); System.out.println(new Person(null)); } catch (IllegalArgumentException e) { System.out.println("Error creating Person: " + e); } } } final class Person { final private String name; public Person(String name) { if (name == null) throw new IllegalArgumentException("null name"); this.name = name; } public String toString() { return "Person(" + name + ")"; }; }
+--------+ name 1 +--------+ | Person |<>-------->| String | +--------+ +--------+