编写一个 Person 类,要求如下: (1)属性:字符串类型的 name(姓名)、整型的 age(年龄)。 (2)有两个参数(name,age)的构造函数。 (3)编写一个静态方法,以对象数组作为形参,返回对象数组中年龄最小的对象。JAVA语言
时间: 2023-12-03 16:43:56 浏览: 81
以下是符合要求的 Person 类的代码:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public static Person getYoungestPerson(Person[] people) {
if (people == null || people.length == 0) {
return null;
}
Person youngestPerson = people[0];
for (int i = 1; i < people.length; i++) {
if (people[i].age < youngestPerson.age) {
youngestPerson = people[i];
}
}
return youngestPerson;
}
// 可以根据需要添加其他方法和属性
}
```
使用示例:
```java
Person p1 = new Person("Alice", 25);
Person p2 = new Person("Bob", 20);
Person p3 = new Person("Charlie", 30);
Person[] people = {p1, p2, p3};
Person youngestPerson = Person.getYoungestPerson(people);
System.out.println("The youngest person is: " + youngestPerson.name);
```
输出结果为:
```
The youngest person is: Bob
```
阅读全文