数组Person,用Java举个例子
时间: 2024-03-15 08:44:50 浏览: 62
好的,下面是一个使用Java语言实现的数组Person例子:
```java
public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Gender: " + gender;
}
}
```
上述代码定义了一个`Person`类,包含属性`name`、`age`和`gender`,还有一个带参构造函数和一些getter和setter方法。接下来,我们可以定义一个`Person`类型的数组来存储多个对象:
```java
public class Main {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person("Alice", 25, "Female");
people[1] = new Person("Bob", 30, "Male");
people[2] = new Person("Charlie", 20, "Male");
for (Person person : people) {
System.out.println(person.toString());
}
}
}
```
在这个例子中,我们定义了一个`Person`类型的数组`people`,并对其进行初始化。然后,我们使用for-each循环遍历数组中的每个对象,并输出其信息。
阅读全文