package model; import java.sql.Date; import java.text.SimpleDateFormat; import java.text.ParseException; public class Human extends Creature{ private String name; private Date dob; /** * Constructor * @param name * @param dob */ public Human(String name, String dob) { super(); this.name = name; if (dob != "") { if (this.isValidDOB(dob)==true) this.dob = Date.valueOf(dob); else throw new IllegalArgumentException("Invalid date of birth."); } } /** * Overloaded Constructor * @param name */ public Human(String name) { this(name,""); // call other constructor } public String getName(){ return this.name; } public int getAge() { if (this.dob!=null) { Date now = new Date(System.currentTimeMillis()); long diff = now.getTime() - this.dob.getTime(); double age = diff / 1000 / 60 /60 / 24 / 365.26; this.setAge((int) age); return (int) age; } else { return super.getAge(); } } public boolean isValidDOB(String dob) { if (dob == null) return false; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); if (dob.trim().length() != df.toPattern().length()) return false; df.setLenient(false); try { //parse the dob parameter df.parse(dob.trim()); } catch (ParseException pe) { return false; } Date d1 = new Date(System.currentTimeMillis()); Date d2 = Date.valueOf(dob); if (d1.before(d2)) // future date? cannot be date of birth. return false; else return true; } }