java语言,编写一个person类,包括人的姓名,性别,年龄,子女等属性,并封装有获得姓名,获得年龄,增加一岁,获得子女,设置子女等方法,其中子女为一个person数组,用某实际数据测试该类的设计
时间: 2024-05-05 08:19:58 浏览: 106
好的,下面是Java代码实现:
```java
public class Person {
private String name;
private String gender;
private int age;
private Person[] children;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void addAge() {
age++;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
}
```
我们可以使用以下代码进行测试:
```java
public class TestPerson {
public static void main(String[] args) {
Person mother = new Person("Mary", "Female", 30);
Person father = new Person("John", "Male", 35);
Person child1 = new Person("Tom", "Male", 5);
Person child2 = new Person("Lily", "Female", 3);
Person[] children = {child1, child2};
mother.setChildren(children);
father.setChildren(children);
System.out.println("Mother's name: " + mother.getName());
System.out.println("Father's age: " + father.getAge());
child1.addAge();
System.out.println("Child1's age: " + child1.getAge());
Person[] childrenOfMother = mother.getChildren();
System.out.println("Children of mother: ");
for (Person child : childrenOfMother) {
System.out.println(child.getName());
}
}
}
```
输出结果为:
```
Mother's name: Mary
Father's age: 35
Child1's age: 6
Children of mother:
Tom
Lily
```
以上就是一个简单的Person类的实现和测试。
阅读全文