binibiningtinamoran

Person

Oct 29th, 2019
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. public class Person {
  2.  
  3.     private int age;
  4.     private String name;
  5.  
  6.     public Person(int age, String name) {
  7.         // WHAT HAPPENS IF AGE ENTERED IS NEGATIVE?!?!
  8.         //this.age = (age > 0) ? age : 0;
  9.         setAge(age);
  10.         this.name = name;
  11.     }
  12.  
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.  
  17.     public void setAge(int age) {
  18.         this.age = Math.max(age, 0);
  19.     }
  20.  
  21.     public String getName() {
  22.         return name;
  23.     }
  24.  
  25.     public void setName(String name) {
  26.         this.name = name;
  27.     }
  28.  
  29.     @Override
  30.     public String toString() {
  31.         return "Name : " + getName() +
  32.                 "Age: "+ getAge();
  33.     }
  34.  
  35.     public int addAges(Person anotherPerson) {
  36.         return anotherPerson.getAge() + this.getAge();
  37.     }
  38.  
  39.     public static void main(String[] args) {
  40.         Person person1 = new Person(23, "Robin");
  41.         Person person2 = new Person(22, "Thomas");
  42.         System.out.println(person1.toString());
  43.         System.out.println(person2.toString());
  44.         System.out.printf("The sum of ages: %,d\n",person1.addAges(person2));
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment