OnJava8-Examples/typeinfo/Position.java

52 lines
1.4 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// typeinfo/Position.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-15 11:47:04 -08:00
import java.util.*;
class EmptyTitleException extends RuntimeException {}
2015-06-15 17:47:35 -07:00
class Position {
private String title;
private Person person;
2017-05-01 14:33:10 -06:00
Position(String jobTitle, Person employee) {
2015-12-15 11:47:04 -08:00
setTitle(jobTitle);
setPerson(employee);
2015-06-15 17:47:35 -07:00
}
2017-05-01 14:33:10 -06:00
Position(String jobTitle) {
2015-12-15 11:47:04 -08:00
this(jobTitle, null);
2015-06-15 17:47:35 -07:00
}
public String getTitle() { return title; }
public void setTitle(String newTitle) {
2015-12-15 11:47:04 -08:00
// Throws EmptyTitleException if newTitle is null:
title = Optional.ofNullable(newTitle)
.orElseThrow(EmptyTitleException::new);
2015-06-15 17:47:35 -07:00
}
public Person getPerson() { return person; }
public void setPerson(Person newPerson) {
2015-12-15 11:47:04 -08:00
// Uses empty Person if newPerson is null:
2017-01-20 21:30:44 -08:00
person = Optional.ofNullable(newPerson)
.orElse(new Person());
2015-06-15 17:47:35 -07:00
}
@Override
public String toString() {
2017-01-20 21:30:44 -08:00
return "Position: " + title +
", Employee: " + person;
2015-12-15 11:47:04 -08:00
}
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);
}
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
2015-12-15 11:47:04 -08:00
/* Output:
Position: CEO, Employee: <Empty>
Position: Programmer, Employee: Arthur Fonzarelli
caught EmptyTitleException
*/