如何使用一个静态变量来跟踪最高年龄

问题描述 投票:-3回答:1

我现在有一个创造的姓名,年龄,电子邮件和SSN,并验证其输入的选项Person类。我怎么会用一个静态变量来跟踪的人进入了最高年龄的?

java variables static
1个回答
0
投票

我想,你们班有这样的方法

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

你想获得最高的同龄人。

添加静态属性的人,在setAge方法比较青睐,如果目前的人比以前或以前是空高,保存当前

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

}

这样你可以得到的最高年龄

int highestAge =   Person.highest.getAge();
© www.soinside.com 2019 - 2024. All rights reserved.