用java定义一个儿童类,构建若干个小朋友对象,并输出有关数据,包括:姓名、性别、年龄、爱好、小孩的个数。
时间: 2024-10-29 21:09:36 浏览: 18
你可以创建一个名为`Child`的Java类来表示儿童,包含姓名(name)、性别(gender)、年龄(age)和爱好的(hobby)属性。为了输出相关信息,我们还需要一个存储所有孩子的列表。以下是相关的代码示例:
```java
public class Child {
private String name;
private String gender;
private int age;
private String hobby;
public Child(String name, String gender, int age, String hobby) {
this.name = name;
this.gender = gender;
this.age = age;
this.hobby = hobby;
}
// getter and setter methods for the properties
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getHobby() { return hobby; }
public void setHobby(String hobby) { this.hobby = hobby; }
@Override
public String toString() {
return "Name: " + name + ", Gender: " + gender + ", Age: " + age + ", Hobby: " + hobby;
}
}
public class Main {
private static List<Child> childrenList = new ArrayList<>();
public static void main(String[] args) {
// 创建几个小朋友并添加到列表中
addChild(new Child("Tom", "男", 5, "画画"));
addChild(new Child("Lily", "女", 7, "跳舞"));
addChild(new Child("Jerry", "男", 6, "足球"));
// 输出所有孩子信息
System.out.println("Number of Children: " + childrenList.size());
for (Child child : childrenList) {
System.out.println(child);
}
}
// 添加一个新的孩子到列表
public static void addChild(Child child) {
childrenList.add(child);
}
}
```
这个例子中,我们在`Main`类里创建了一个`childrenList`来存储`Child`对象,并通过`addChild`方法添加新孩子。在`main`方法中,我们打印出孩子的总数以及每个孩子的详细信息。
阅读全文