用java编写代码,要求编写一个Person类,包括人的姓名、性别、年龄、子女等属性,并封装有获得姓名、获得年龄、增加1岁、获得子女、设置子女等方法,其中子女为一个Prson 数组。用某实际数据测试该类的设计。
时间: 2023-05-28 09:04:02 浏览: 98
public class Person {
private String name;
private String gender;
private int age;
private Person[] children;
public Person(String name, String gender, int age, Person[] children) {
this.name = name;
this.gender = gender;
this.age = age;
this.children = children;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void increaseAge() {
age++;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
public static void main(String[] args) {
Person child1 = new Person("Tom", "Male", 5, null);
Person child2 = new Person("Lucy", "Female", 3, null);
Person[] children = {child1, child2};
Person parent = new Person("John", "Male", 30, children);
System.out.println("Parent name: " + parent.getName());
System.out.println("Parent age: " + parent.getAge());
parent.increaseAge();
System.out.println("Parent age after increase: " + parent.getAge());
System.out.println("Children:");
for (Person child : parent.getChildren()) {
System.out.println(child.getName() + " " + child.getAge() + " " + child.getGender());
}
}
}
阅读全文