2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/Person.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
|
|
|
// Using Optional with regular classes.
|
2015-11-11 20:20:04 -08:00
|
|
|
import onjava.*;
|
2015-12-15 11:47:04 -08:00
|
|
|
import java.util.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
class Person {
|
2015-12-15 11:47:04 -08:00
|
|
|
public final Optional<String> first;
|
|
|
|
public final Optional<String> last;
|
|
|
|
public final Optional<String> address;
|
2015-06-15 17:47:35 -07:00
|
|
|
// etc.
|
2015-12-15 11:47:04 -08:00
|
|
|
public final boolean empty;
|
2015-06-15 17:47:35 -07:00
|
|
|
public Person(String first, String last, String address){
|
2015-12-15 11:47:04 -08:00
|
|
|
this.first = Optional.ofNullable(first);
|
|
|
|
this.last = Optional.ofNullable(last);
|
|
|
|
this.address = Optional.ofNullable(address);
|
|
|
|
empty = !this.first.isPresent()
|
|
|
|
&& !this.last.isPresent()
|
|
|
|
&& !this.address.isPresent();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-12-15 11:47:04 -08:00
|
|
|
public Person(String first, String last) {
|
|
|
|
this(first, last, null);
|
|
|
|
}
|
|
|
|
public Person(String last) { this(null, last, null); }
|
|
|
|
public Person() { this(null, null, null); }
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
|
|
|
public String toString() {
|
2015-12-15 11:47:04 -08:00
|
|
|
if(empty)
|
|
|
|
return "<Empty>";
|
|
|
|
return (first.orElse("") +
|
|
|
|
" " + last.orElse("") +
|
|
|
|
" " + address.orElse("")).trim();
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-12-15 11:47:04 -08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
System.out.println(new Person());
|
|
|
|
System.out.println(new Person("Smith"));
|
|
|
|
System.out.println(new Person("Bob", "Smith"));
|
|
|
|
System.out.println(new Person("Bob", "Smith",
|
|
|
|
"11 Degree Lane, Frostbite Falls, MN"));
|
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:
|
|
|
|
<Empty>
|
|
|
|
Smith
|
|
|
|
Bob Smith
|
|
|
|
Bob Smith 11 Degree Lane, Frostbite Falls, MN
|
|
|
|
*/
|