简体   繁体   中英

How do I use a static variable to keep track of highest age

I currently have a Person class with the options of creating a name, age, email, and ssn, and validating their inputs. How would I use a static variable to keep track of the highest age entered for Person?

I suppose that your class have a method like

public void setAge(int age){
   this.age = age;
}

and you want get the highest age person.

Add a static attribute Person, and in setAge method compare ages if the current person is higher than previous or previous is null, save the current

public class Person {

  private int age;

  // other attrs
  // ...

  public static Person highest;

  public void setAge(int age){
     this.age = age;
     if (highest == null || this.age > highest.getAge()){
        highest = this;
     }
  }

   // getters and setters

}

in this way you can get the highest age

int highestAge =   Person.highest.getAge();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM