forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPosition.java
More file actions
50 lines (48 loc) · 1.44 KB
/
Position.java
File metadata and controls
50 lines (48 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// reflection/Position.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
class EmptyTitleException extends RuntimeException {}
class Position {
private String title;
private Person person;
Position(String jobTitle, Person employee) {
setTitle(jobTitle);
setPerson(employee);
}
Position(String jobTitle) {
this(jobTitle, null);
}
public String getTitle() { return title; }
public void setTitle(String newTitle) {
// Throws EmptyTitleException if newTitle is null:
title = Optional.ofNullable(newTitle)
.orElseThrow(EmptyTitleException::new);
}
public Person getPerson() { return person; }
public void setPerson(Person newPerson) {
// Uses empty Person if newPerson is null:
person = Optional.ofNullable(newPerson)
.orElse(new Person());
}
@Override public String toString() {
return "Position: " + title +
", Employee: " + person;
}
public static void main(String[] args) {
System.out.println(new Position("CEO"));
System.out.println(new Position("Programmer",
new Person("Arthur", "Fonzarelli")));
try {
new Position(null);
} catch(Exception e) {
System.out.println("caught " + e);
}
}
}
/* Output:
Position: CEO, Employee: <Empty>
Position: Programmer, Employee: Arthur Fonzarelli
caught EmptyTitleException
*/