OnJava8-Examples/typeinfo/Position.java

51 lines
1.5 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// typeinfo/Position.java
2015-12-15 11:47:04 -08:00
// (c)2016 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.
// Visit http://mindviewinc.com/Books/OnJava/ 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;
public 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
}
public 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:
person =
Optional.ofNullable(newPerson).orElse(new Person());
2015-06-15 17:47:35 -07:00
}
@Override
public String toString() {
2015-12-15 11:47:04 -08:00
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);
}
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
*/